bashadvanced113 snippets

Git: The Emergency Kit

Messed up the code? Save this guide. Essential commands to undo mistakes, revert commits and save your job.

Sections8
1

📊 Status and History

20 snippets

Commands 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.

bash
git status -s

Status 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.

bash
git status --porcelain

Include 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.

bash
git status --ignored

Branch 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.

bash
git status --branch

Show 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.

bash
git status --show-stash

Full 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.

bash
git log --oneline --graph --all --decorate

Log 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.

bash
git log --stat

Log 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.

bash
git log --patch

Log 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.

bash
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.

bash
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.

bash
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.

bash
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.

bash
git log --follow arquivo.txt

Log 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.

bash
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.

bash
git log --oneline --decorate --graph

Log 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.

bash
git log --reverse

View 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.

bash
git show HEAD

View 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).

bash
git show HEAD~2

View Only Modified File Names

Shows only the names of files that were modified in the specified commit, without displaying the full diff.

bash
git show --name-only HEAD

View Commit with Statistics

Displays modification statistics for the specified commit, showing which files were changed and the number of lines added/deleted.

bash
git show --stat HEAD
2

🌿 Advanced Branches

15 snippets

Essential 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>`.

bash
git checkout -b feature/nova-funcionalidade

Create 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.

bash
git switch -c feature/nova-funcionalidade

List 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`).

bash
git branch -a

List Only Remote Branches

Lists only remote branches. Useful for seeing which branches exist in remote repositories without cluttering the output with local ones.

bash
git branch -r

List 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.

bash
git branch -v

List Merged Branches

Lists branches that have already been fully merged into the current branch. Generally, these are branches that can be safely deleted.

bash
git branch --merged

List 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.

bash
git branch --no-merged

Delete 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.

bash
git branch -d feature-branch

Force 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.

bash
git branch -D feature-branch

Delete 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.

bash
git push origin --delete feature-branch

Rename Current Branch

Renames the local branch `old-name` to `new-name`. If `old-name` is omitted, renames the current branch.

bash
git branch -m old-name new-name

Force Branch Rename

Forces the renaming of a branch, even if `new-name` already exists. Use with caution to avoid overwriting existing branches.

bash
git branch -M old-name new-name

Show Current Branch

Displays the name of the current branch you are working on. Useful for scripts or to quickly confirm the branch.

bash
git branch --show-current

Branches Containing a Specific Commit

Lists all branches that contain the specified commit (e.g., `abc123`). Useful for tracking where a specific commit was integrated.

bash
git branch --contains abc123

Sort 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.

bash
git branch --sort=-committerdate
3

🔄 Merge and Rebase

13 snippets

Commands 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.

bash
git merge feature-branch

Merge 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.

bash
git merge --no-ff feature-branch

Squash 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.

bash
git merge --squash feature-branch

Interactive 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.

bash
git rebase -i HEAD~3

Interactive 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`.

bash
git rebase -i main

Continue Rebase

Continues the rebase process after resolving merge conflicts or after editing a commit during an interactive rebase.

bash
git rebase --continue

Cancel 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.

bash
git rebase --abort

Cherry-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.

bash
git cherry-pick abc123

Cherry-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.

bash
git cherry-pick abc123..def456

Cherry-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.

bash
git cherry-pick --no-commit abc123

Cherry-pick with Origin Credit

Applies commit `abc123` and adds a line "cherry-picked from commit abc123" to the new commit message, indicating the origin.

bash
git cherry-pick -x abc123

Cherry-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.

bash
git cherry-pick --signoff abc123

Cancel 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.

bash
git cherry-pick --abort
4

🔍 Search and Investigation

16 snippets

Powerful 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.

bash
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.

bash
git grep "função" HEAD~5

Search 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.

bash
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.

bash
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.

bash
git blame arquivo.txt

Blame 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.

bash
git blame -L 10,20 arquivo.txt

File 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.

bash
git log -p arquivo.txt

File 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.

bash
git log --follow arquivo.txt

Start 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.

bash
git bisect start

Mark Current Commit as "Bad"

Marks the current commit (HEAD) as "bad", indicating that the bug is present at this point.

bash
git bisect bad HEAD

Mark 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.

bash
git bisect good v1.0.0

Automate 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".

bash
git bisect run npm test

Finish Bisect

Finishes the `git bisect` session and returns the branch to the commit it was on before starting the bisect.

bash
git bisect reset

Visualize Bisect Graph

Opens a graphical interface (if configured) to visualize the commit graph and bisect progress.

bash
git bisect visualize

Show Bisect Log

Shows the log of all `git bisect` commands executed in the current session, useful for reviewing the process.

bash
git bisect log

Repeat Bisect from a Log

Repeats a bisect session from a previously saved log file, allowing the debugging process to be recreated.

bash
git bisect replay arquivo.log
5

🏷️ Tags and Releases

13 snippets

Commands 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.

bash
git tag v1.0.0

Create 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.

bash
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.

bash
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.

bash
git tag

Filter Tags

Lists tags that match a specific pattern (e.g., all tags starting with "v1.").

bash
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.

bash
git show v1.0.0

Delete Local Tag

Deletes tag `v1.0.0` from the local repository. This does not remove the tag from remote repositories.

bash
git tag -d v1.0.0

Delete Remote Tag

Deletes the `v1.0.0` tag from the remote repository `origin`. This is necessary to remove published tags.

bash
git push origin --delete v1.0.0

Push Specific Tag to Remote

Pushes a specific tag (`v1.0.0`) to the remote repository `origin`. Tags are not automatically pushed with `git push`.

bash
git push origin v1.0.0

Push All Tags to Remote

Pushes all local tags to the remote repository `origin`. Useful for publishing multiple tags at once.

bash
git push origin --tags

Verify 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.

bash
git tag -v v1.0.0

Create Signed Tag

Creates an annotated and GPG-signed tag. The signature ensures the authenticity and integrity of the tag.

bash
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.

bash
git tag -f v1.0.0
6

📦 Advanced Stash

13 snippets

Commands 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.

bash
git stash

Stash with Message

Saves changes with a descriptive message. The message helps identify the stash's content later, especially when there are multiple stashes.

bash
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.

bash
git stash push -- arquivo.txt

Stash Including Untracked Files

Saves changes, including untracked files, to the stash. Useful for saving the entire working directory state.

bash
git stash push --include-untracked

List Stashes

Lists all currently stored stashes, showing a brief description and the index of each (e.g., `stash@{0}`).

bash
git stash list

View Stash Changes

Displays a summary of the changes contained in a specific stash (e.g., `stash@{0}`). Shows which files were modified.

bash
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.

bash
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.

bash
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.

bash
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.

bash
git stash drop stash@{0}

Clear All Stashes

Removes all stashes from the stack. Use with extreme caution, as this action is irreversible.

bash
git stash clear

Create 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.

bash
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.

bash
git stash --keep-index
7

↩️ Reset and Restore

9 snippets

Powerful 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.

bash
git reset --soft HEAD~1

Mixed 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.

bash
git reset --mixed HEAD~1

Hard 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!

bash
git reset --hard HEAD~1

Restore 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`.

bash
git restore arquivo.txt

Unstage 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.

bash
git restore --staged arquivo.txt

Restore 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.

bash
git restore --source=HEAD~1 arquivo.txt

View 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.

bash
git reflog

Branch Reflog History

Displays the reflog for a specific branch (e.g., `main`), showing all times the `main` reference was updated.

bash
git reflog show main

Revert 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`.

bash
git reset --hard HEAD@{2}
8

☁️ Remote and Collaboration

14 snippets

Advanced 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.

bash
git remote -v

Add 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.

bash
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.

bash
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.

bash
git remote remove upstream

Fetch All Remotes

Downloads objects and references from all configured remote repositories. Does not integrate changes into the working directory, only updates local remote references.

bash
git fetch --all

Fetch 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.

bash
git fetch --prune

Pull 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.

bash
git pull --rebase

Pull 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.

bash
git pull --ff-only

Push 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.

bash
git push -u origin feature-branch

Safe 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.

bash
git push --force-with-lease

Delete 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.

bash
git push origin :feature-branch

Push All Branches

Pushes all local branches to the remote repository `origin`. Useful to ensure all your branches are synchronized with the remote.

bash
git push --all origin

Mirror 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.

bash
git push --mirror origin

Push 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.

bash
git push --tags --follow-tags

Get the latest articles delivered to your inbox.

Follow Us: