Git: The Emergency Kit
Messed up the code? Save this guide. Essential commands to undo mistakes, revert commits and save your job.
Sections8
📊 Status and History
20 snippetsCommands to check the current repository state, explore commit history in advanced ways, and view changes in specific files or commits. Essential for understanding workflow and debugging history.
Short Status
Displays the status of the working directory and staging area concisely. The -s (or --short) flag shows the output in an abbreviated, easy-to-read format, indicating modified, added, or deleted files.
git status -sStatus for Scripts (Porcelain)
Provides status output formatted to be easily parsed by scripts. It is a stable interface not designed for human readability, ideal for automation.
git status --porcelainInclude Ignored Files in Status
Includes ignored files (listed in .gitignore) in the status output, showing them in the "Untracked files" section. Useful for checking if ignore rules are working as expected.
git status --ignoredBranch Information in Status
Displays additional information about the current branch, such as the branch name, whether it's ahead or behind its upstream, and the current commit hash.
git status --branchShow Stashes in Status
Shows the number of stashes you currently have. Useful for remembering if there are saved changes that need to be applied or removed.
git status --show-stashFull History Log
Provides a complete and compact view of the commit history. `--oneline` shows each commit on one line, `--graph` draws an ASCII graph of the history, `--all` includes remote branches and tags, and `--decorate` shows branch and tag names.
git log --oneline --graph --all --decorateLog with Statistics
Displays statistics for each commit, showing which files were modified and the number of lines added/deleted. Useful for a quick overview of each commit's impact.
git log --statLog with Full Diff (Patch)
Shows the full diff (patch) for each commit, displaying the exact line-by-line changes. Essential for reviewing the content of each change.
git log --patchLog by Period
Filters the commit history to show only those made within a specific period. Formats like "2 weeks ago", "yesterday", "2023-01-01" can be used.
git log --since="2 weeks ago"Log by Author
Filters the history to display only commits made by a specific author. The author's name must match the one configured in Git.
git log --author="nome"Log by Commit Message
Filters the commit history by a keyword or regex pattern in the commit message. Useful for finding commits related to bug fixes or specific features.
git log --grep="fix"Log by Code Change (Pickaxe)
Searches for commits that introduced or removed a specific string in the code (also known as the "pickaxe" option). It's powerful for tracking where a function or variable was first changed.
git log -S "função"Log Following File Renames
Displays the history of a specific file, following its history through renames. Ensures you see all changes to the file, even if its name has changed.
git log --follow arquivo.txtLog Colorido e Formatado
Apresenta um log de commits altamente formatado e colorido, exibindo hash, branches/tags, mensagem, data relativa e autor. Personalizável para uma melhor legibilidade visual.
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'Compact Log with Graph
A compact and decorated view of the history, showing the graph of branches and tags. Similar to the full log, but without including all remote references by default.
git log --oneline --decorate --graphLog in Reverse Chronological Order
Displays the commit history in reverse chronological order, i.e., from the oldest commit to the most recent. Useful for seeing the evolution of a project.
git log --reverseView Last Commit
Shows the content of the last commit on the current branch, including the diff. It's a quick way to review what was most recently committed.
git show HEADView Specific Commit (HEAD~2)
Displays the content of the commit that is two commits before HEAD. Any commit reference can be used (hash, tag, branch, HEAD~n).
git show HEAD~2View Only Modified File Names
Shows only the names of files that were modified in the specified commit, without displaying the full diff.
git show --name-only HEADView Commit with Statistics
Displays modification statistics for the specified commit, showing which files were changed and the number of lines added/deleted.
git show --stat HEAD🌿 Advanced Branches
15 snippetsEssential commands for creating, listing, managing, and deleting branches, both local and remote. Fundamental for collaborative development and workflow organization.
Create and Switch to New Branch (Checkout)
Creates a new branch with the specified name (e.g., `feature/new-feature`) and immediately switches to it. It's a shortcut for `git branch <name>` followed by `git checkout <name>`.
git checkout -b feature/nova-funcionalidadeCreate and Switch to New Branch (Switch)
Modern and more intuitive command to create a new branch and switch to it. It is the recommended alternative to `git checkout -b` for this purpose.
git switch -c feature/nova-funcionalidadeList All Branches (Local and Remote)
Lists all branches, including local and remote ones. Remote branches are prefixed with the remote name (e.g., `remotes/origin/main`).
git branch -aList Only Remote Branches
Lists only remote branches. Useful for seeing which branches exist in remote repositories without cluttering the output with local ones.
git branch -rList Branches with Last Commit
Lists local branches with additional information, such as the last commit of each branch and the commit message. Helps to get a quick overview of each branch's state.
git branch -vList Merged Branches
Lists branches that have already been fully merged into the current branch. Generally, these are branches that can be safely deleted.
git branch --mergedList Unmerged Branches
Lists branches that have not yet been merged into the current branch. These branches contain work that has not yet been integrated and should not be deleted carelessly.
git branch --no-mergedDelete Local Branch (Safe)
Deletes the specified local branch (e.g., `feature-branch`). This is a "safe delete" that will fail if the branch contains unmerged commits into the current branch.
git branch -d feature-branchForce Delete Local Branch
Forces the deletion of the specified local branch, even if it contains unmerged commits. Use with caution, as it may result in loss of work.
git branch -D feature-branchDelete Remote Branch
Deletes a branch from the remote repository (e.g., `origin/feature-branch`). It's the command to remove remote branches that are no longer needed.
git push origin --delete feature-branchRename Current Branch
Renames the local branch `old-name` to `new-name`. If `old-name` is omitted, renames the current branch.
git branch -m old-name new-nameForce Branch Rename
Forces the renaming of a branch, even if `new-name` already exists. Use with caution to avoid overwriting existing branches.
git branch -M old-name new-nameShow Current Branch
Displays the name of the current branch you are working on. Useful for scripts or to quickly confirm the branch.
git branch --show-currentBranches Containing a Specific Commit
Lists all branches that contain the specified commit (e.g., `abc123`). Useful for tracking where a specific commit was integrated.
git branch --contains abc123Sort Branches by Last Commit Date
Lists local branches sorted by the date of the last commit, from most recent to oldest. The `-` flag reverses the order.
git branch --sort=-committerdate🔄 Merge and Rebase
13 snippetsCommands for integrating changes between branches through traditional merge or reorganizing history with rebase. Includes cherry-pick for applying specific commits.
Normal Merge
Integrates changes from `feature-branch` into the current branch. If possible, performs a fast-forward merge; otherwise, creates a merge commit.
git merge feature-branchMerge Without Fast-Forward
Forces the creation of a merge commit, even if a fast-forward merge was possible. This preserves the branch history, explicitly showing where the feature was integrated.
git merge --no-ff feature-branchSquash Merge
Applies changes from `feature-branch` to the current branch as a single commit, without recording the `feature-branch` in the history. The commits from `feature-branch` are "squashed" into a single commit on the target branch.
git merge --squash feature-branchInteractive Rebase (Last N Commits)
Starts an interactive rebase on the last 3 commits from HEAD. Allows reordering, editing, squashing, splitting, or removing commits. Opens a text editor with the options.
git rebase -i HEAD~3Interactive Rebase (From a Branch)
Starts an interactive rebase of all commits on the current branch that are not on the `main` branch. Useful for cleaning up history before merging into `main`.
git rebase -i mainContinue Rebase
Continues the rebase process after resolving merge conflicts or after editing a commit during an interactive rebase.
git rebase --continueCancel Rebase
Cancels the ongoing rebase and returns the branch to its state before the rebase started. Useful if you decide not to continue or encounter insoluble problems.
git rebase --abortCherry-pick Specific Commit
Applies the changes introduced by a specific commit (e.g., `abc123`) to the current branch, creating a new commit with those changes. Useful for porting specific fixes or features.
git cherry-pick abc123Cherry-pick Commit Range
Applies a range of commits (from `abc123` exclusive to `def456` inclusive) to the current branch. Useful for porting multiple changes at once.
git cherry-pick abc123..def456Cherry-pick Without Creating Commit
Applies the changes from commit `abc123` to the working directory and staging area, but without creating a new commit. Allows reviewing and adjusting changes before committing them.
git cherry-pick --no-commit abc123Cherry-pick with Origin Credit
Applies commit `abc123` and adds a line "cherry-picked from commit abc123" to the new commit message, indicating the origin.
git cherry-pick -x abc123Cherry-pick with Sign-off
Applies commit `abc123` and adds a line "Signed-off-by: Your Name <your.email@example.com>" to the new commit message, indicating that you certify the origin of the change.
git cherry-pick --signoff abc123Cancel Cherry-pick
Cancels an ongoing cherry-pick and returns the branch to its previous state. Useful if there are conflicts or if the cherry-pick is no longer desired.
git cherry-pick --abort🔍 Search and Investigation
16 snippetsPowerful tools for searching within source code, investigating line-by-line modification history, and using git bisect to identify the commit that introduced a bug.
Search String in Working Tree
Searches for a string or regex pattern in Git-tracked files in the working directory. It's like a traditional `grep`, but optimized for Git repositories.
git grep "função"Search String in Specific Commit
Searches for a string or regex pattern in the code within a specific commit (e.g., `HEAD~5`). Useful for finding where a string existed at an earlier point in history.
git grep "função" HEAD~5Search String with Line Numbers
Searches for a string and displays the line numbers where the match was found. Helps quickly locate the occurrence in the file.
git grep -n "função"Search String Case Insensitive
Performs a case-insensitive search, ignoring the difference between uppercase and lowercase letters when looking for the string.
git grep -i "função"Blame: Who Modified Each Line
Shows the line-by-line revision history for a specific file. For each line, it displays the commit that last modified it, the author, and the date. Useful for identifying who and when changed a part of the code.
git blame arquivo.txtBlame Specific Lines
Restricts the output of `git blame` to a specific range of lines (from line 10 to 20, inclusive) of a file. Useful for focusing on a problematic section.
git blame -L 10,20 arquivo.txtFile History with Patches
Displays the history of commits that affected `arquivo.txt`, including the full patch (diff) of each change. Allows seeing exactly how the file evolved.
git log -p arquivo.txtFile History Following Renames
Displays the history of a specific file, following its history through renames. Ensures you see all changes to the file, even if its name has changed.
git log --follow arquivo.txtStart Bisect for Bugs
Starts a `git bisect` session, which is a tool to find the commit that introduced a bug using a binary search through the history.
git bisect startMark Current Commit as "Bad"
Marks the current commit (HEAD) as "bad", indicating that the bug is present at this point.
git bisect bad HEADMark Known Version as "Good"
Marks a known commit (e.g., `v1.0.0`) as "good", indicating that the bug was not present at this point. Git then chooses an intermediate commit for you to test.
git bisect good v1.0.0Automate Bisect with Tests
Automates the bisect process by running a script or command (e.g., `npm test`) on each commit. The script must return 0 for "good" and an error code (1-127) for "bad".
git bisect run npm testFinish Bisect
Finishes the `git bisect` session and returns the branch to the commit it was on before starting the bisect.
git bisect resetVisualize Bisect Graph
Opens a graphical interface (if configured) to visualize the commit graph and bisect progress.
git bisect visualizeShow Bisect Log
Shows the log of all `git bisect` commands executed in the current session, useful for reviewing the process.
git bisect logRepeat Bisect from a Log
Repeats a bisect session from a previously saved log file, allowing the debugging process to be recreated.
git bisect replay arquivo.log🏷️ Tags and Releases
13 snippetsCommands for creating, listing, and managing tags — immutable references to specific points in repository history, typically used for marking software versions or releases.
Create Lightweight Tag
Creates a lightweight tag named `v1.0.0` on the current commit. Lightweight tags are just a pointer to a commit.
git tag v1.0.0Create Annotated Tag
Creates an annotated tag named `v1.0.0` with a descriptive message. Annotated tags are full Git objects, containing the tagger's name, email, date, and message, and are recommended for releases.
git tag -a v1.0.0 -m "Release 1.0.0"Create Annotated Tag on Specific Commit
Creates an annotated tag `v1.0.0` on a specific commit (e.g., `abc123`), instead of HEAD. Useful for marking past commits.
git tag -a v1.0.0 abc123 -m "Tag commit específico"List All Tags
Lists all tags in the local repository in alphabetical order.
git tagFilter Tags
Lists tags that match a specific pattern (e.g., all tags starting with "v1.").
git tag -l "v1.*"View Tag Details
Displays the details of a specific tag, including the tag message (if annotated) and the commit it points to.
git show v1.0.0Delete Local Tag
Deletes tag `v1.0.0` from the local repository. This does not remove the tag from remote repositories.
git tag -d v1.0.0Delete Remote Tag
Deletes the `v1.0.0` tag from the remote repository `origin`. This is necessary to remove published tags.
git push origin --delete v1.0.0Push Specific Tag to Remote
Pushes a specific tag (`v1.0.0`) to the remote repository `origin`. Tags are not automatically pushed with `git push`.
git push origin v1.0.0Push All Tags to Remote
Pushes all local tags to the remote repository `origin`. Useful for publishing multiple tags at once.
git push origin --tagsVerify Tag Signature
Verifies the GPG signature of an annotated tag. Requires the tag to have been signed and the signatory's GPG key to be available.
git tag -v v1.0.0Create Signed Tag
Creates an annotated and GPG-signed tag. The signature ensures the authenticity and integrity of the tag.
git tag -s v1.0.0 -m "Release"Force Tag Creation/Update
Forces the creation or update of an existing tag. Use with caution, as it can overwrite important tags.
git tag -f v1.0.0📦 Advanced Stash
13 snippetsCommands for managing Git stash, a temporary area to store uncommitted changes when you need to switch branches or handle an interruption.
Basic Stash
Saves uncommitted changes (modifications in the working directory and staged files) to a stash stack, reverting the working directory to the state of the last commit. Untracked files are not included by default.
git stashStash with Message
Saves changes with a descriptive message. The message helps identify the stash's content later, especially when there are multiple stashes.
git stash push -m "WIP: feature X"Stash Specific File
Saves only the changes of a specific file to the stash, leaving other files unchanged. The `--` is necessary to distinguish the file path from other options.
git stash push -- arquivo.txtStash Including Untracked Files
Saves changes, including untracked files, to the stash. Useful for saving the entire working directory state.
git stash push --include-untrackedList Stashes
Lists all currently stored stashes, showing a brief description and the index of each (e.g., `stash@{0}`).
git stash listView Stash Changes
Displays a summary of the changes contained in a specific stash (e.g., `stash@{0}`). Shows which files were modified.
git stash show stash@{0}View Full Stash Patch
Shows the full patch (diff) of a specific stash, displaying line-by-line changes. Essential for reviewing content before applying.
git stash show -p stash@{0}Apply Stash Without Removing
Applies the changes from a specific stash to the working directory, but keeps the stash on the stack. Useful if you want to apply the same stash to multiple branches.
git stash apply stash@{0}Apply and Drop Stash
Applies the changes from a specific stash to the working directory and then removes the stash from the stack. It's the most common command for applying and cleaning stashes.
git stash pop stash@{0}Remove Specific Stash
Removes a specific stash from the stack without applying its changes. Useful for discarding stashes that are no longer needed.
git stash drop stash@{0}Clear All Stashes
Removes all stashes from the stack. Use with extreme caution, as this action is irreversible.
git stash clearCreate Branch From Stash
Creates a new branch from the commit where the stash was created, applies the stash to it, and then removes the stash from the stack. Useful for continuing work from a stash on a new branch.
git stash branch nova-branch stash@{0}Stash Only Unstaged Changes
Saves unstaged changes to the stash, but keeps changes that were already in the staging area. Useful for committing only part of the changes and stashing the rest.
git stash --keep-index↩️ Reset and Restore
9 snippetsPowerful commands to undo changes, revert commit history, and recover previous files or states. Includes git reset (with caution variations) and git restore (modern, safer command).
Soft Reset (Undo Commit, Keep Staged)
Undoes the last commit, moving HEAD to the previous commit, but keeps the changes from the undone commit in the staging area. The working directory remains unchanged.
git reset --soft HEAD~1Mixed Reset (Undo Commit and Staging)
Undoes the last commit and moves the changes from the undone commit to the working directory (unstaged). This is the default behavior of `git reset` if no flag is specified. The staging area is cleared.
git reset --mixed HEAD~1Hard Reset (DELETES EVERYTHING! Be careful!)
Undoes the last commit, discards all changes from the undone commit from the working directory and staging area. This action is irreversible and can result in loss of uncommitted work. Use with extreme caution!
git reset --hard HEAD~1Restore File in Working Tree
Discards changes to `arquivo.txt` in the working directory, restoring it to the state of the last commit. It's a safer and more intuitive alternative to `git checkout -- arquivo.txt`.
git restore arquivo.txtUnstage File (Remove from Staging)
Removes `arquivo.txt` from the staging area, moving its changes back to the working directory (unstage). The file in the working directory remains unchanged.
git restore --staged arquivo.txtRestore File from Specific Commit
Restores `arquivo.txt` in the working directory and staging area to the state it was in at a specific commit (e.g., `HEAD~1`). Useful for recovering old file versions.
git restore --source=HEAD~1 arquivo.txtView Reference History (Reflog)
Displays a log of all actions that modified the local repository's HEAD. It's a history of "where HEAD has been," allowing recovery of commits that seem to have been lost after resets or rebases.
git reflogBranch Reflog History
Displays the reflog for a specific branch (e.g., `main`), showing all times the `main` reference was updated.
git reflog show mainRevert Using Reflog
Reverts HEAD (and the current branch) to a previous state recorded in the reflog (in this case, the second most recent state). It's the primary way to recover commits after an accidental `git reset --hard`.
git reset --hard HEAD@{2}☁️ Remote and Collaboration
14 snippetsAdvanced commands for managing remote repositories, syncing branches, and collaborating effectively on Git projects.
List Remotes (Verbose)
Lists the remote repositories configured for the project, showing their names and URLs (verbose). Useful for checking where you are pulling from and pushing to.
git remote -vAdd New Remote
Adds a new remote repository named `upstream` with the specified URL. Common for setting up a remote for the original repository in a fork.
git remote add upstream https://...Change Remote URL
Changes the URL of an existing remote repository (e.g., `origin`). Useful for updating a repository's location or switching between SSH and HTTPS.
git remote set-url origin https://...Remove Remote
Removes a remote repository named `upstream` from the local configuration. This does not affect the remote repository itself.
git remote remove upstreamFetch All Remotes
Downloads objects and references from all configured remote repositories. Does not integrate changes into the working directory, only updates local remote references.
git fetch --allFetch with Prune (Remove Deleted Refs)
Removes local references to remote branches that were deleted in the remote repository. Helps keep the list of remote branches clean and up-to-date.
git fetch --prunePull with Rebase
Downloads changes from the remote repository and then applies your local changes on top of them using rebase. This avoids unnecessary merge commits and maintains a linear history.
git pull --rebasePull Only Fast-Forward
Downloads changes from the remote repository and attempts a fast-forward merge. If a fast-forward is not possible (i.e., there are local commits that are not ancestors of the remote), the command fails, requiring a manual merge or rebase.
git pull --ff-onlyPush and Set Upstream
Pushes the `feature-branch` to the remote repository `origin` and sets it as the upstream branch. This allows using `git pull` and `git push` without specifying the remote and branch later.
git push -u origin feature-branchSafe Force Push (with-lease)
Pushes changes to the remote repository, forcing history overwrite, but with a safeguard. It only works if the remote branch has not been updated by someone else since your last fetch, preventing accidental overwrites of others' work.
git push --force-with-leaseDelete Remote Branch (Push)
Deletes the `feature-branch` from the remote repository `origin`. The `:` before the local branch name indicates that you are pushing "nothing" to the remote branch, effectively deleting it.
git push origin :feature-branchPush All Branches
Pushes all local branches to the remote repository `origin`. Useful to ensure all your branches are synchronized with the remote.
git push --all originMirror Repository to Remote
Mirrors the local repository to the remote repository `origin`. This means that all local branches, tags, and references will be replicated to the remote, including the deletion of anything not present locally. Use with extreme caution, as it is a destructive operation.
git push --mirror originPush with Tags and Follow-Tags
Pushes all local tags to the remote repository, and also pushes any commits referenced by those tags (if not already on the remote). `--follow-tags` ensures that annotated tags pointing to commits that haven't been pushed yet are also pushed.
git push --tags --follow-tagsRelated cheatsheets
Get-LocationPowerShell: Automate the Boring Stuff
GUIs are for amateurs. Master the One-Liners and Pipelines that manage 100 servers simultaneously. Stop clicking windows and start treating your infrastructure as code.
docker --versionDocker: Production Commands
Forget manual configuration. Copy and paste commands to spin up containers, clean volumes and deploy in record time.
ping -c 4 google.comLinux Networking: The Hacker Guide
Feel like Mr. Robot. Network commands to discover IPs, open ports and diagnose connections like a CyberSec professional.