Git Advanced Commands Quick Reference Guide

Production-ready guide covering git advanced commands quick reference guide with implementation patterns, code examples, and anti-patterns for enterprise engineering teams.

Git Advanced Commands Quick Reference Guide

This reference collects the git commands you’ll reach for when the happy path ends and you need to rewrite, recover, or inspect history without starting over. It matters whenever a force‑push is blocked, a merge stalls, a commit lands in the wrong branch, or you need to restructure commits before a review. The following sections are organized by the problem you’re trying to solve, not by command taxonomy, with exact flags, real error text, and the gotchas that catch people off guard.

Rewriting History Safely

Interactive rebase with autosquash

When you need to fold a freshly‑written commit into an earlier one without launching an editor, git rebase -i with autosquash does the heavy lifting. Set the config once:

git config --global rebase.autosquash true

Then, name your commit subject line to match an existing commit’s fixup! or squash! prefix:

git commit -m "fixup!original/commit/subject"
git commit -m "squash!original/commit/subject"

Running git rebase -i HEAD~N will automatically reorder and mark those commits. When the editor opens, every fixup line is pre‑filled to drop the commit message, and squash lines keep the message for editing.

Exact command:

git rebase -i --autosquash HEAD~3

Sharp edge: If the autosquash branch diverges from the upstream base (e.g., new commits were pushed while you were rebasing), git aborts with:

fatal: failed to push some refs to 'remote'

The rebase completes locally, but you must git push --force-with-lease to update the remote, otherwise the next fetch rewinds your work.

git commit --amend with --no-edit

To tack a staged change onto the most recent commit without touching its message:

git commit --amend --no-edit

Exact error when the index is clean:

nothing to commit, working tree clean

In that case git commit --amend opens the editor with the existing message; adding --no-edit silently fails to amend and exits with status 0 but no changes.

git reset vs git revert vs git checkout

These three are the core “undo” primitives, and confusing them is the single most common source of data loss.

GoalCommandWhat it does
Undo public commits, preserve historygit revert <commit>Creates a new commit that inverts the changes. Safe for shared branches.
Undo local, unpushed commits, discard changesgit reset --hard <commit>Moves the branch pointer and wipes the working tree. Irreversible without reflog.
Switch branches or restore filesgit checkout <branch> / git checkout <file>Moves HEAD or restores a single file from another branch or commit.

Exact error text:

$ git reset --hard HEAD~1
HEAD is now at abc1234 Old commit
$ git reset --soft HEAD~1
HEAD is now at abc1234 Old commit
$ git revert HEAD
[master abc1234] Revert "Add feature X"

Sharp edge: git reset --hard on a branch that has an upstream tracking branch will not update the remote. The local branch pointer moves, but git push may refuse or push a divergent history. Always check git log --oneline --graph --decorate --all after a hard reset to confirm where you land.

Recovering Lost Commits

The reflog

Every action that moves HEAD, updates a ref, or checks out a branch is recorded in the local reflog, independent of any remote. It’s the first place to look after a reset --hard, a rebased branch, or a force‑push gone wrong.

Exact command:

git reflog

Typical output:

abc1234 HEAD@{0}: reset: moving to HEAD~1
def5678 HEAD@{1}: commit: Add feature Y  2 hours ago
ghi9012 HEAD@{2}: checkout: moving from feature-y to main

To recover a commit you thought was gone:

git checkout -b recovered-branch abc1234

Sharp edge: The reflog is local to the repository and expires after 30 days (configurable via gc.reflogExpire). If you clone a repo and the reflog has already been garbage‑collected, the commit is gone unless it’s reachable from a remote ref or another branch.

git fsck & the lost‑and‑found

When a commit isn’t in the reflog but still exists as an unreferenced object, git fsck --unreachable surfaces it.

Exact command:

git fsck --unreachable --no-reflogs

Output includes lines like:

unreachable blob a1b2c3d4
unreachable commit deadbeef

To inspect or recover:

git show deadbeef
git checkout -b recovered-branch deadbeef

Sharp edge: git fsck is I/O intensive on large repos and may take minutes. On a repo with millions of objects, it can emit thousands of “unreachable” lines, making it easy to miss the one you actually need. Pair it with git log --walk-reflogs to narrow the scope.

Inspecting & Debugging

Pretty‑formatted git log

Standard git log output is often too verbose or not machine‑friendly for scripting or quick checks. The --format flag lets you emit exactly what you need.

Exact command (one‑line per commit, with author, relative date, and subject):

git log --format="%h %ad | %s%d" --date=short

Exact output:

a1b2c3d | 2024-03-15 | refactor(auth): clean up auth flow (tag: v1.2)
def4e5f | 2024-03-10 | feat: add dark mode (tag: v1.1)

Sharp edge: %ad defaults to the commit author date. If you need committer date, use %cd with --date=short. Mixing %h (abbreviated hash) with full %H can produce confusing diffs when scripts parse the output.

git blame with line‑range debugging

When a bug was introduced in the last week and you know roughly which file, git blame with -L limits the scan and speeds up the query.

Exact command:

git blame -L 42,58 -- path/to/file.py

Exact output (abridged):

^42 SomeFunction
43    x = 1
44    y = 2
...
58    return x + y

The ^ prefix indicates the line was introduced in the very first commit of the file.

Sharp edge: git blame against a very large file on a slow filesystem can stall. The command reads the full revision graph for the file; on repos with hundreds of contributors per file, it may take seconds to minutes. Caching is per‑repository and does not persist across clones.

git diff with --cached and --no-index

To compare the staging area against the working tree, or two arbitrary files on disk (not under git), use --cached or --no-index.

Exact command (staged vs working tree):

git diff --cached

Exact command (two arbitrary files on disk):

git diff --no-index /path/to/a.txt /path/to/b.txt

Exact output:

--- a.txt
+++ b.txt
@@ -1,3 +1,3 @@
-line1
+LINE1
 line3

Sharp edge: --no-index does not treat the files as git objects; it runs a simple byte‑wise diff. If the files are large, the output can be massive. Also, --no-index ignores .gitignore and any git‑specific metadata.

Branch, Merge & Remote Mastery

git worktree for side‑step development

When you need to switch branches or test a hotfix without stashing or committing half‑finished work, git worktree checks out a second working directory tied to the same repo.

Exact commands:


git worktree add ../hotfix-fix main

# List existing worktrees
git worktree list

Exact output:

/path/to/repo on main [master] (/path/to/repo)
/path/to/repo/hotfix-fix on hotfix-branch (detached at abc1234)

Sharp edge: Worktrees require a filesystem that supports hard links (most Linux/macOS, Windows via Git For Windows 2.30+). On FAT32 or network mounts that don’t support hard links, git worktree add fails with:

fatal: Unable to create hardlink, because this filesystem does not support it

Also, worktrees share the same .git directory. A git gc or git prune in one worktree can unexpectedly remove objects needed by another.

git submodule update & sync

Submodules are independent repos checked out at a specific commit. Keeping them current requires explicit commands.

Exact commands:

# Initialize and clone all submodules
git submodule update --init --recursive

# Sync submodule tracking info from the index
git submodule sync

# Update a single submodule to the latest commit recorded in the parent
git submodule update --remote path/to/submodule

Exact error when submodule is uninitialized:

fatal: bad repository path /path/to/repo (ownership or permission problem?)

Sharp edge: git submodule update --remote fetches the remote’s HEAD and checks it out, which may advance the submodule beyond the commit recorded in the parent. This changes the parent’s tree and requires a subsequent git commit in the parent repo. Forgetting to commit the updated submodule pointer is the most common source of “submodule out of sync” bugs.

Merge strategies and the “unrelated histories” wall

When merging two branches that share no common ancestor, git refuses by default.

Exact command and error:

git merge feature-branch
fatal: refusing to merge unrelated histories

Exact fix:

git merge feature-branch --allow-unrelated-histories

Sharp edge: Using --allow-unrelated-histories creates a merge commit with two distinct roots. The resulting history can be confusing for git log --graph and may cause issues with tools that expect a single linear ancestry (e.g., some CI bisect implementations). Only use this when you intentionally merged two independent projects or recovered from a broken clone.

Cleanup & Housekeeping

git gc & git prune

Git’s built‑in garbage collector removes unreachable objects. Running it manually is rarely needed, but sometimes useful after a massive reset --hard or rebase that left many dangling commits.

Exact command:

git gc --prune=now

Exact output (summary):

Counting objects: 12345, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (8912/8912), done.
Writing objects: 100% (12345/12345), done.
Total 12345 (delta 5432), reused 8765 (delta 3210)

Sharp edge: git gc --prune=now removes everything not reachable from any ref, including stashed changes that were never popped and reflog entries past the expiration window. If you’ve just done a reset --hard and immediately gc, the dropped commits may be permanently gone before you realize you needed them. Always check the reflog first.

Pruning stale remote‑tracking branches

After a teammate deletes a branch on the remote, your local refs/remotes/origin/ still lists it. git remote prune cleans those up.

Exact command:

git remote prune origin

Exact output:

Pruning origin
 * [deleted]         origin/feature/old-thing
 * [deleted]         origin/exp/experiment

Sharp edge: git remote prune only removes remote‑tracking refs. It does not delete any local branches that tracked those remote branches. If you had a local feature/old-thing that was tracking origin/feature/old-thing, the local branch remains after pruning, but its upstream is now gone. You’ll see:

Branch 'feature/old-thing' set up to track nonexistent remote branch 'origin/feature/old-thing'.

Re‑set the upstream with git branch -u origin/main or remove the local branch entirely if it’s no longer needed.

Sharp Edges: What Silently Fails & Confused Options

git pull vs git fetch + git merge/rebase

A quiet pitfall: git pull runs git fetch then git merge by default. If your local branch has diverged from the remote tracking branch, the merge commit may introduce a “merge” that wasn’t intended, especially on feature branches where you wanted a rebase workflow.

Exact command to force rebase:

git pull --rebase

If rebase conflicts arise, git pauses and lets you resolve, then continues with git rebase --continue. If you instead run git pull (merge), the conflict resolution flow is the same, but the history records a merge commit where a rebase would have rewritten the line‑line history.

Sharp edge: Once a merge commit exists from a git pull without --rebase, git pull --rebase thereafter will refuse until you either rebase manually or reset the branch. The safeguard prevents accidental double‑merges, but it can confuse teams accustomed to always‑pull‑merge habits.

git cherry-pick across divergent branches

Cherry‑picking a commit that was itself a merge, or that introduces conflicts with the target branch, can leave the index in a state where git status shows no changes but the commit isn’t recorded.

Exact command:

git cherry-pick abc1234

Exact error when conflict:

error: could not apply abc1234... Some commit
hint: After resolving the conflicts,
hint: mark the resolved files with 'git add <file>' and run 'git cherry-pick --continue'.
hint: or, to abandon the cherry-pick entirely, run 'git cherry-pick --abort'.

Sharp edge: After git cherry-pick --abort, the branch returns to its pre‑cherry‑pick state, but any changes you made to the working tree before the cherry‑pick start are not automatically restored. If you edited files, those edits persist. Always git stash before a delicate cherry‑pick if you might need the workspace clean.

Configuration key collisions: pull.rebase vs branch.rebase

Two config keys influence pull behavior, and mixing them causes surprising results.

Config keyScopeEffect
pull.rebaseGlobal (all pulls)git pull behaves as git pull --rebase
branch.<name>.rebasePer‑branchOverrides global pull.rebase for that branch only

Exact check:

git config pull.rebase
# output: true
git config branch/main.rebase
# output: false

Sharp edge: When both are set, the per‑branch value wins. A developer may set pull.rebase = true globally, then forget that a specific feature branch has branch/feature.rebase = false (the default). The next git pull on that feature branch does a merge instead of a rebase, creating an unexpected merge commit. Document the per‑branch setting in your team’s contributing guide, or avoid the global flag entirely and pass --rebase or --no-rebase explicitly.

git rebase --onto misuse

The --onto flag re‑bases a range of commits onto a new base, but its semantics are easy to misapply, especially when the source branch has commits you don’t want moved.

Exact command (rebase commits reachable from feature onto main, skipping the merge base):

git rebase --onto main feature~3 feature

This takes the last 3 commits of feature, removes them from their current base, and reapplies them on top of main. The first feature~3..feature range is rewritten; commits outside that range stay put.

Sharp edge: If feature has diverged significantly from main, --onto may introduce duplicate commits or cause git rebase to abort with:

Cannot rebase: Some commits are already based on the target branch.

A safer pattern for most workflows is git rebase main (which rebases the entire current branch onto main). Use --onto only when you need to cherry‑pick a subset of history without touching the rest.

Final checklist before you run anything

These commands and edge notes cover the most frequently needed advanced git operations, the exact interfaces you’ll type, and the production‑grade failure modes that tend to surface when things go sideways. Keep this file bookmarked, and the next time a rebase stalls or a commit vanishes, you’ll have the right tool and the right warning at your fingertips.

This page was rewritten on 26 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at hello@thegarnetwiki.com and we will correct it.