Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Git Advanced (Rebase, Bisect, Worktree)

Beyond add/commit/push — rewrite history cleanly, hunt a bug with binary search, and juggle branches without stashing.

Everything here rests on one model: commits are immutable snapshots, a branch is a movable pointer to one of them, and “rewriting history” really means making new commits and moving the pointer. The old commits are not destroyed at once. git reflog logs every position HEAD and each branch have held, kept for weeks by default, which is why nearly every mistake on this page can be undone.

The real danger is sharing rewritten commits, because anyone who built on the old hashes has to untangle them. Rewrite freely on private branches, revert on shared ones, and publish rewrites with --force-with-lease.

beforeABCDEmainfeatfeat was cut from B;main moved on to Creplayedafter: git rebase mainABCD'E'mainfeatsame changes, new hashesDEold D, E: no branch, in reflog
A rebase copies, it does not move. D and E are replayed onto C as new commits and the branch label jumps to the copies. The originals still exist, which is why reflog and ORIG_HEAD can undo it.

Rebase & rewrite

git rebase main
replay your commits on top of main — linear history, no merge commit
git rebase -i HEAD~5
squash, reword, reorder or drop the last 5 commits in an editor
git commit --amend
fold staged changes into the last commit; --no-edit keeps the message
git commit --fixup <sha>
record a fix for an older commit; git rebase -i --autosquash folds it in
rebase.autoSquash true
set with git config so every rebase -i moves fixup!/squash! commits into place
git rebase --onto A B
move the commits after B onto A — transplant a branch cut from the wrong base
git rebase --update-refs
also move stacked branches that point into the rebased range (Git 2.38+)
git rebase -x CMD main
run CMD after each replayed commit and stop at the first failure
git rebase --continue
resume after fixing and git add-ing a conflict; --abort restores the start
rerere.enabled true
set with git config: Git records conflict fixes and replays them next time
Golden rule
Never rebase commits you’ve pushed and shared — it rewrites hashes.

Find the bad commit

git bisect start
binary-search history: mark git bisect bad and git bisect good <sha>
git bisect run npm test
automate it: exit 0 = good, 1–127 = bad, 125 = skip this commit
git bisect skip · reset
skip a commit you cannot test · finish and return to where you started
git blame -L 10,20 file
who last touched lines 10–20; -w ignores whitespace, -C follows moved code
git blame --ignore-rev X
look past a formatting commit; list such commits in .git-blame-ignore-revs
git log -S "name"
pickaxe: commits that added or removed that string — when it appeared or vanished
git log -G "regex"
commits whose diff touches lines matching a regex, even if occurrence counts stay equal
git log -L :func:file
the history of one function, commit by commit
git log --follow file
one file’s history, continuing across renames
git show <sha>:path
print a file as it was at that commit — no checkout needed

Read history

git log --oneline --graph
branch topology at a glance; add --all to include every branch
git log main..feat
commits on feat that are not on main — what a merge would bring in
git diff main...feat
three dots: changes on feat since it forked — what the pull request shows
git range-diff old...new
compare two versions of a rebased branch, e.g. origin/feat...feat
git shortlog -sn
commit counts per author; --no-merges leaves merge commits out
git log --author=ann
filter by author; combine with --since="2 weeks ago" and -- path/

Move work around

git cherry-pick <sha>
copy one commit onto the current branch; -x notes where it came from
git cherry-pick A^..B
copy a range including A; A..B would leave A out
git stash push -m msg
stash with a label; -u includes untracked files, -- path stashes just that path
git stash pop · apply
restore and drop · restore and keep; stash@{2} picks an older stash
git stash list · show -p
see what is stashed; git stash show -p stash@{1} prints one as a diff
git stash branch new
turn a stash into a branch from the commit it was made on — sidesteps conflicts
git worktree add ../hf
a second checkout in its own folder — no stashing; a branch lives in one worktree at a time
git worktree list
every checkout of this repo and the branch each one holds
git worktree remove DIR
delete a worktree; git worktree prune tidies up after one removed by hand
git switch -
back to the previous branch; git switch -c new creates a branch

Undo safely

git restore --staged f
unstage a file, keeping the edits
git restore file
discard unstaged edits to the file (gone for good)
git restore -s HEAD~2 f
bring back a file as it was two commits ago
git revert <sha>
new commit that inverts an old one — the safe undo for shared history
git revert -m 1 <merge>
undo a merge commit; merging that branch again later means reverting this revert
git reset --soft HEAD~1
uncommit, keep the changes staged
git reset HEAD~1
uncommit and unstage (the default --mixed); edits stay in your files
git reset --hard <sha>
move the branch and throw away every uncommitted change — stash first if unsure
ORIG_HEAD
where HEAD was before the last merge, rebase or reset: git reset --hard ORIG_HEAD
git reflog
every place HEAD has been; find the lost commit, then git reset --hard <sha>
git clean -n · -fd
preview · delete untracked files and directories; -x also deletes ignored files
git fsck --lost-found
list dangling commits — how a dropped stash is recovered

Share rewritten history

--force-with-lease
force-push only if the remote is where you last saw it — no clobbering a teammate
--force-if-includes
add to the lease so a background git fetch cannot quietly defeat it (2.30+)
git pull --rebase
rebase onto upstream instead of a merge bubble; pull.rebase true makes it the default
git push -u origin HEAD
publish the current branch under the same name and track it
git checkout --theirs f
take one side of a conflicted file; during a rebase ours and theirs are swapped

Big repos

git clone --depth 1
shallow clone of the latest commit; git fetch --unshallow fetches the rest
--filter=blob:none
partial clone: full history, file contents fetched on demand — good for monorepos
git sparse-checkout set
check out only listed directories, e.g. git sparse-checkout set apps/web
git maintenance start
schedule background prefetch, gc and commit-graph upkeep for this repo

Worked example: transplant a branch cut from the wrong base

You branched feat off topic, a teammate’s unfinished cache work, instead of main. Your two date-parsing commits must ship without theirs. A plain git rebase main would carry the cache commits along, because they are also missing from main.

$ git log --oneline --graph --all
* 078646c Add date tests
* 6d6781b Fix date parsing
* 6385e3d WIP: cache tests
* af42681 WIP: new cache layer
| * 1cbeef3 Release 1.4
|/
* 3b87cbf Initial
  1. Name exactly what should move. topic..feat is “on feat, not on topic”:
    $ git log --oneline topic..feat
    078646c Add date tests
    6d6781b Fix date parsing
  2. Replay that range onto main. The arguments read as: onto main, everything after topic, up to feat.
    $ git rebase --onto main topic feat
    Successfully rebased and updated refs/heads/feat.
    $ git log --oneline --graph --all
    * d8130ae Add date tests
    * d096886 Fix date parsing
    * 1cbeef3 Release 1.4
    | * 6385e3d WIP: cache tests
    | * af42681 WIP: new cache layer
    |/
    * 3b87cbf Initial
  3. Check that the copies carry the same changes. ORIG_HEAD still names the old tip:
    $ git range-diff topic..ORIG_HEAD main..feat
    1:  6d6781b = 1:  d096886 Fix date parsing
    2:  078646c = 2:  d8130ae Add date tests

= means each patch is identical. A ! would flag a commit whose diff changed during conflict resolution. topic is untouched, so your teammate loses nothing.

Recipes

Clean up a feature branch before review

git fetch origin
git rebase -i --autosquash origin/main
git range-diff origin/feature...feature
git push --force-with-lease --force-if-includes

Fold fixups and reword commits against the latest main, check the rewrite commit by commit, then publish it without overwriting anyone else’s push.

Find the commit that broke the tests

git bisect start HEAD v1.4.0
git bisect run npm test
git bisect reset

HEAD is known bad and v1.4.0 known good, so bisect tests about log2(n) midpoints and names the first bad commit. Make the test script exit 125 on commits that cannot build.

Undo a bad rebase or reset

git reflog -n 10
git reset --hard HEAD@{3}

Pick the entry from just before the operation (here, three moves ago) and point the branch back at it. --hard discards uncommitted work, so stash it first.

Ship a hotfix without stashing your feature

git worktree add -b hotfix ../hotfix origin/main
cd ../hotfix
git commit -am "Fix crash on empty input"
git push -u origin hotfix
cd - && git worktree remove ../hotfix

The hotfix gets its own directory and branch, so the half-finished feature stays exactly as it was. A branch can be checked out in only one worktree at a time.

Recover a deleted file from history

git log --diff-filter=D --oneline -- path/to/file.py
git restore --source=<sha>^ -- path/to/file.py

The first command finds the commit that deleted the file; restoring from its parent (^) brings back the last version that existed.

When to use it, and when not

  • Interactive rebase pays off before review, on a branch only you have pushed to. Reviewers read a story of small commits instead of “wip” and “fix”. If the team squash-merges every PR, main never sees those commits, so tidy for the reviewer and stop there.
  • Bisect needs two things: a known-good commit and a test that answers the same way every time. A flaky test gives one wrong answer and sends the search into the wrong half. If you have no good commit, try an old release tag first.
  • Cherry-pick suits one or two commits, such as a fix backported to a release branch. To move a whole run of commits, rebase --onto is clearer and keeps their order.
  • Worktree beats stash when both versions must run at once, such as comparing old and new behaviour side by side or keeping a long test run going while you start something else.

Trade-offs and limits

Big-repo options trade download size for network trips later:

CloneFetched up frontWhat it costs
--depth 1the latest commit onlylog, blame and bisect stop at the cut
--filter=blob:noneevery commit and tree, no file contentsblame, log -p and checking out old commits download contents on demand
--filter=tree:0commits onlyany history walk fetches trees too; suited to one-off CI builds, not daily work
sparse-checkout(pair it with a partial clone)only listed folders exist on disk, so a repo-wide search misses the rest

Rebase has a cost of its own. It replays conflicts one commit at a time, so a 10-commit branch can stop on the same clash several times, where a merge resolves it once. rerere softens that. Every rewrite also changes hashes, so links to old commits in a pull request stop matching.

Common mistakes

  • Losing merge commits in a rebase. By default rebase drops merge commits and flattens the branch. Pass --rebase-merges when the merges carry meaning.
  • A bisect script that fails for the wrong reason. If a commit does not build and the script exits 1, bisect marks it bad and can name the wrong culprit. Exit 125 for “cannot test”; any code of 128 or more aborts the whole run.
  • Forgetting git bisect reset. You are left on a detached HEAD at some midpoint, and commits made there belong to no branch.
  • Deleting a worktree folder with rm -rf. Git still believes the branch is checked out there and refuses to check it out anywhere else. git worktree prune clears the stale entry.
  • Swapping the --onto arguments. The order is new base, old base, branch. Run git log --oneline OLD..BRANCH first: that list is exactly what will move.

Check yourself

HEAD is bad and HEAD~15 is good. How many tests does git bisect run perform?

Four. Sixteen commits are in play and each test halves them: 16 → 8 → 4 → 2 → 1. For about 1,000 commits it would take 10 (210 = 1,024).

Which commits does git rebase -i HEAD~3 open, and in what order?

The last three commits, oldest at the top. The list runs top to bottom, so moving a line up makes that commit happen earlier.

Your git bisect run script crashes with exit code 200. What does bisect do?

It stops. Codes of 128 and above abort the run (“exit code 200 … is < 0 or >= 128”) and leave the bisect where it was. Use 125 to skip a commit and 1 to mark it bad.

Rebasing feat onto main stops on a conflict in app.js. Whose version does git checkout --ours app.js take?

Main’s. A rebase replays your commits on top of main, so “ours” is the base being built on and “theirs” is your own commit, the reverse of a merge.

Questions about Git Advanced (Rebase, Bisect, Worktree) Cheat Sheet

What is the difference between git reset and git revert?

git reset moves the current branch pointer to another commit, optionally resetting the index (mixed, the default) and the working tree (hard). Commits after that point drop out of the branch, so it rewrites history. git revert leaves history alone and adds a new commit that applies the inverse of an earlier one. Use reset for local work nobody else has pulled, and revert for anything already pushed to a shared branch, because a reset there forces everyone else to reconcile their copies after your force-push.

When should I rebase instead of merge?

Rebase when you want a clean, linear history on a branch only you work on: replaying your commits on top of the latest main makes the pull request easier to review and easier to bisect later. Merge when the branch is shared or long-lived, or when you want history to record exactly when work came together. The rule that keeps teams out of trouble is never to rebase commits someone else may have built on. Many teams rebase privately and then merge or squash-merge the finished branch into main.

How do I undo a git rebase?

Right after the rebase, ORIG_HEAD still points at where the branch was before it started, so git reset --hard ORIG_HEAD restores it. If you have run other commands since, use git reflog: it lists every position HEAD has held, with entries such as rebase (start). Find the line just before the rebase began and reset to that entry, for example HEAD@{5}. Both forms discard uncommitted work, so stash or commit it first. If you had already force-pushed the rebased branch, push the restored one with --force-with-lease.

What does git push --force-with-lease do?

It force-pushes only if the remote branch still points where your last fetch saw it. If a teammate pushed in the meantime, the push is refused instead of silently deleting their commits, which is what a plain --force would do. The protection can be defeated by a background fetch, for example from an editor, because that updates your view of the remote without you ever looking at the new commits. Adding --force-if-includes, available since Git 2.30, closes that gap by also requiring the remote tip to be in your local history.