Advanced Git: Rebasing, Internals, and Real-World Workflows
(opens full-size image in a new tab)Introduction
This is Part 2 of a three-part series. Part 1 covered the everyday loop — staging, committing, branching, merging, undoing mistakes, and working with a remote. If any of those feel shaky, that post is the place to start; everything here builds directly on that mental model of working directory → staging area → repository, and branches as cheap, movable pointers.
This post covers the tools you reach for once a repo gets real: rewriting history safely before sharing it, applying individual commits with precision, finding the exact commit that broke something, and understanding what Git is actually doing under the hood — which turns "undo commands feel scary" into "I know exactly how to get this back."
By the end, you'll be comfortable with:
- Rebasing — including interactive rebase, and when not to reach for it
- Checking a rebase with
range-diff, and rebasing stacked branches in one go cherry-pickandbisectfor surgical history operations- Git's internal object model — what a commit, branch, and tag actually are
- Submodules, worktrees, hooks, commit signing, and productivity config
- Recovering "lost" work with
git reflog - Real branching workflows — Git Flow, GitHub Flow, trunk-based development
Rebasing
Rebasing replays your branch's commits on top of a different base commit, producing a cleaner, linear history than a merge commit would.
git switch feature/login
git rebase main # replay feature/login's commits on top of main's latest commit
git rebase --continue # after resolving a conflict mid-rebase
git rebase --skip # skip the commit currently causing a conflict
git rebase --abort # bail out entirely, back to the pre-rebase state
git rebase --onto main old-base feature # replay only commits since old-base, onto maingit rebase main uses your local main, which is only as fresh as your last pull — rebasing onto a stale main is an easy mistake. git sync fetches first, fast-forwards main without checking it out, and rebases your branch onto it in one command.
Interactive Rebase
The single most powerful history-editing tool in Git — lets you reorder, edit, combine, or drop commits before they're shared.
git rebase -i HEAD~5 # interactively edit the last 5 commits
git rebase -i main # interactively edit everything since diverging from mainThis opens an editor listing your commits, oldest first, each with an action:
pick a1b2c3d Add login form
squash e4f5g6h Fix typo in login form
reword h7i8j9k Add validation
fixup k1l2m3n Remove console.log
drop n4o5p6q WIP: experiment (not needed)--autosquash automates the common "small fix for an earlier commit" case:
git commit --fixup=abc1234 # creates a commit clearly marked as a fixup for abc1234
git rebase -i --autosquash main # automatically reorders and marks it "fixup" for youThe git fixup alias in Git Aliases Worth Adding to Your ~/.gitconfig runs both steps in one command, with no editor to step through.
Checking What a Rebase Changed: git range-diff
After an interactive rebase, git log shows you the result, but not how it differs from what you had before. Every commit has a new SHA, so an ordinary git diff between the old and new tips only tells you how the final trees differ. It can't tell you which commit you reworded, which one you dropped, or whether a conflict resolution quietly changed a line. git range-diff (Git 2.19+) compares two versions of the same series of commits, commit by commit.
git range-diff main @{1} HEAD # the branch before the rebase vs after it, both measured from main
git range-diff main feature@{1} feature # the same, naming the branch instead of using the current one
git range-diff feature@{1}...feature # three-dot shorthand, with no base to name
git range-diff origin/feature...feature # what you're about to force-push vs what's on the remote@{1} is the current branch's previous position from its reflog. A finished rebase moves the branch once, so @{1} is exactly where it was before you started. If you've committed or reset since, look up the right entry with git reflog first.
Say you rebased feature/login onto the latest main, dropped a debug-logging commit, tightened a constant in the rate-limiting commit, and added a new commit along the way:
1: 34ef006 = 1: a702aa7 Add login form
2: b0644cb = 2: 661ad0e Add validation
3: 7d4e010 < -: ------- Add debug logging
4: 69e6448 ! 3: 851f620 Add rate limiting
@@ Commit message
## rate-limit.js (new) ##
@@
+// Lock an account after too many failed logins.
-+const MAX_ATTEMPTS = 5;
++const MAX_ATTEMPTS = 3;
+const WINDOW_MS = 15 * 60 * 1000;
-: ------- > 4: e60a6a5 Add remember-me optionEach line pairs a commit from the old range (left) with its match in the new range (right). For a changed commit, the indented block is a diff of the two diffs: the outer -/+ column is what changed between the versions, and the inner one is the patch itself.
Rebasing Stacked Branches: --update-refs
Splitting a large change into a stack of dependent branches keeps each pull request reviewable: feature/api holds the API client, and feature/ui is built on top of it. The catch is that rebasing the top branch onto a newer main replays feature/api's commits too, but leaves the feature/api branch pointing at the old ones. --update-refs (Git 2.38+) moves every branch that points into the rebased range along with it.
git switch feature/ui
git rebase --update-refs main # rebases feature/ui AND moves feature/api to its replayed commits
git push --force-with-lease origin feature/api feature/ui
git config --global rebase.updateRefs true # make it the default for every rebaseIn an interactive rebase, each branch that will be moved gets its own update-ref line in the todo list. Delete a line to leave that branch where it is:
pick 1a2b3c4 Add API client
pick 5d6e7f8 Add retry logic
update-ref refs/heads/feature/api
pick 9a0b1c2 Add login screen
pick 3d4e5f6 Wire login screen to the API clientBranches checked out in another worktree are never moved this way. Switch that worktree to a different branch first if you want it included.
Testing Every Commit: git rebase --exec
-x (or --exec) runs a shell command after each commit is replayed, and stops the rebase as soon as one fails. It's the quickest way to make sure every commit in a branch builds and passes its tests on its own, not just the final one, which keeps the history usable for git bisect later.
git rebase -x "npm test" main # run the test suite after every replayed commit
git rebase -x "npm run lint" -x "npm test" HEAD~5 # several -x options run in order, after each commit
git rebase -i -x "npm test" main # adds an exec line under every pick in the todo listWhen a command fails, Git stops on that commit with your branch half-rebased:
Executing: npm test
warning: execution failed: npm test
You can fix the problem, and then run
git rebase --continueFix the problem, git commit --amend it into the commit that broke, then git rebase --continue. Git doesn't run the failed command again on its own; pass --reschedule-failed-exec if you want it to re-run before moving on.
Cherry-Picking
Applies the changes from a specific commit onto your current branch — useful for pulling in one fix without merging an entire branch.
git cherry-pick abc1234 # apply one commit onto the current branch
git cherry-pick abc1234 def5678 # apply several commits, in the order given
git cherry-pick abc1234^..def5678 # apply a range of commits (exclusive of abc1234 itself)
git cherry-pick -n abc1234 # apply the changes, but don't commit — stage them for review first
git cherry-pick -x abc1234 # append "(cherry picked from commit abc1234)" to the message
git cherry-pick --continue # after resolving a conflict
git cherry-pick --abort # bail out entirelyMerge Strategy Options: -X ours and -X theirs
When two branches edit the same lines, Git stops with a conflict. If you already know which side should win, -X passes an option to the merge strategy so it resolves those hunks for you. Everything that doesn't conflict is still merged normally.
git merge -X ours feature/config # conflicting hunks resolve to the current branch's version
git merge -X theirs feature/config # conflicting hunks resolve to feature/config's version
git merge -X ignore-all-space feature # treat whitespace-only differences as no change at all
git merge -X ignore-space-change feature # ignore changes in the amount of whitespace
git merge -X renormalize feature # normalise line endings on both sides before mergingcherry-pick, rebase and revert accept the same -X options, so git cherry-pick -X theirs abc1234 applies a fix and lets its version win any conflicting lines.
Three similar-looking commands do quite different things, and mixing them up can silently throw work away:
| Command | What it does |
|---|---|
git merge -X ours feature | A real merge: takes every non-conflicting change from feature, and resolves only the conflicting hunks in favour of your branch |
git merge -s ours feature | A different strategy: records a merge commit but keeps your tree exactly as it is, discarding all of feature's changes |
git checkout --ours file.txt | Used mid-conflict: replaces one file with your side's version, leaving the rest of the merge to you |
Finding the Commit That Introduced a Bug: git bisect
Binary-searches through history to find the exact commit that introduced a bug.
git bisect start
git bisect bad # the current commit is broken
git bisect good v1.2.0 # this earlier tag/commit was known-good
# Git checks out a commit halfway between — test it, then tell it the result:
git bisect good # this commit is fine, search the newer half
git bisect bad # this commit is broken, search the older half
# ...repeat until Git reports the exact first-bad commit
git bisect reset # done — return to your original branchBisect is the right tool when you can test for the bug. When you already know which line or string is involved, searching history is usually faster — Searching Git History: git log -S, -L, git grep and git blame shows how to find the commit that changed it with git log -S, git log -L and git blame.
Rewriting History Safely
Beyond interactive rebase, a few more tools exist specifically for cleaning up history before sharing it.
git rebase -i --root # interactively rewrite EVERY commit, from the very first one
git commit --squash=abc1234 # like --fixup, but keeps this commit's message for review during squash
git filter-repo --path secrets.env --invert-paths # (separate tool) permanently remove a file from all historyIts pitfalls are around rewriting file contents, though. A rewrite that only touches commit metadata — like resetting each commit's committer date to its author date after a rebase, which git fix-dates does — never changes a tree, so the bundled filter-branch is still a reasonable fit there.
Submodules & Subtrees
Two different ways to embed one Git repository inside another.
Submodules
A submodule is a pointer to a specific commit of another repository — the two histories stay entirely separate.
git submodule add https://github.com/user/lib.git libs/lib
git submodule init # after cloning a repo that already has submodules
git submodule update # check out the commit each submodule is pinned to
git submodule update --init --recursive # do both, recursively, in one step
git submodule foreach 'git pull origin main' # run a command inside every submoduleSubtrees
A subtree copies another repository's history directly into yours, as a subdirectory — one combined history, no separate pointer to manage.
git subtree add --prefix=libs/lib https://github.com/user/lib.git main --squash
git subtree pull --prefix=libs/lib https://github.com/user/lib.git main --squash
git subtree push --prefix=libs/lib https://github.com/user/lib.git mainWorktrees
Lets you check out multiple branches at once, each in its own directory, all backed by the same .git history — no need to stash or commit WIP just to switch context.
git worktree add ../hotfix hotfix/urgent-bug # new working directory, on an existing branch
git worktree add -b feature/new ../new-feature # new working directory AND new branch, together
git worktree list # see every linked worktree
git worktree remove ../hotfix # done with it — clean upGit Internals: Objects, Refs, and the .git Directory
Part 1 introduced commits as snapshots and branches as pointers, at the level you need to use Git day-to-day. Here's what that actually looks like on disk.
Git's entire history is a content-addressable key-value store of four object types, all identified by the SHA-1 (or, on newer repos, SHA-256) hash of their contents.
| Object | Contains |
|---|---|
| blob | A single file's raw content (no filename, no metadata) |
| tree | A directory listing — names + modes, pointing at blobs and other trees |
| commit | A pointer to one tree (the snapshot), one or more parent commits, author/committer, and a message |
| tag | An annotated tag's metadata, pointing at a commit |
Here's how those objects actually link together for a small project:
Plumbing Commands
The commands you've used so far ("porcelain") are built on lower-level "plumbing" commands that operate on these objects directly:
git cat-file -p HEAD # pretty-print any object's raw content, by hash or ref
git cat-file -t abc1234 # print an object's type (blob / tree / commit / tag)
git hash-object src/index.js # compute the SHA a file's content WOULD get, without storing it
git rev-parse HEAD # resolve any ref/shorthand to its full SHA
git ls-tree HEAD # list a commit's top-level tree entries
git update-ref refs/heads/main abc1234 # move a branch pointer directly (what `git reset` uses internally)The .git Directory, Briefly
.git/
├── HEAD # currently "ref: refs/heads/main" — a pointer to a pointer
├── config # this repo's local config (git config --local)
├── index # the staging area, in binary form
├── objects/ # every blob/tree/commit/tag, content-addressed by hash
├── refs/
│ ├── heads/ # one file per local branch, containing a commit SHA
│ └── tags/ # one file per tag
└── logs/ # the reflog — see below.gitattributes
Part 1 covered .gitignore for excluding untracked files. .gitattributes is its sibling — controlling per-path behavior for files that are tracked: line endings, diff/merge strategy, and what counts as generated code.
* text=auto # normalize line endings for text files, leave binaries alone
*.png binary # never diff, never normalize — treat as opaque binary
package-lock.json -diff # tracked normally, but excluded from diffs (generated file)
*.min.js linguist-generated # hint to GitHub's diff UI: this is generated, collapse it by defaultHooks
Scripts Git runs automatically at specific points — stored in .git/hooks/, and (unlike everything else in .git) not cloned or versioned along with the repo by default.
.git/hooks/pre-commit # runs before a commit is created — great for linting/formatting
.git/hooks/commit-msg # runs after the message is written — enforce a message format
.git/hooks/pre-push # runs before a push leaves your machine — run the test suiteA minimal pre-commit hook (make it executable with chmod +x):
#!/bin/sh
npm run lint || {
echo "Lint failed — commit aborted."
exit 1
}Signing Commits and Tags
Git takes user.name and user.email on trust, so anyone can make a commit that claims to be from you. A signature proves the commit or tag was made with a key you hold. Since Git 2.34 that key can be the SSH key you already use to push, so there's no separate GPG setup to maintain.
git config --global gpg.format ssh # sign with SSH instead of GPG
git config --global user.signingkey ~/.ssh/id_ed25519.pub # the public half of the key to sign with
git config --global commit.gpgSign true # sign every commit by default
git config --global tag.gpgSign true # sign every annotated tag by defaultDespite the gpg in their names, these settings cover SSH signing too. Without the two defaults, sign individual commits and tags explicitly:
git commit -S -m "Add rate limiting" # sign one commit
git tag -s v1.0.0 -m "Release 1.0.0" # create a signed, annotated tagTo check SSH signatures locally, Git needs an allowed signers file that maps email addresses to the keys trusted to sign for them:
echo "you@example.com $(cat ~/.ssh/id_ed25519.pub)" >> ~/.config/git/allowed_signers
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
git log --show-signature -1 # show the latest commit with its signature status
git verify-commit HEAD # exit status 0 only if the signature is good
git tag -v v1.0.0 # verify a signed tagcommit 9c192a2b75d253f8e45854f49097b2b713f03bc5
Good "git" signature for you@example.com with ED25519 key SHA256:RsJoLzTqSsu/n69HYoHhQpf/lJeww0MsnCe6zk8zmXI
Author: Your Name <you@example.com>
Date: Mon Nov 23 10:20:35 2026 +0530
Add rate limitingFor GPG instead, leave gpg.format unset (it defaults to openpgp) and set user.signingkey to your key's ID from gpg --list-secret-keys --keyid-format=long. Every other command above works the same way.
Aliases & Productivity Config
Aliases turn long, frequent commands into muscle memory.
git config --global alias.co switch
git config --global alias.st status -sb
git config --global alias.lg "log --oneline --graph --all"
git config --global alias.amend "commit --amend --no-edit"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.unstage "restore --staged"These end up in ~/.gitconfig and can also be edited directly:
[alias]
co = switch
st = status -sb
lg = log --oneline --graph --allFor a fuller, tested set — one-step fixups, WIP parking, safe force-pushes, and more — see Git Aliases Worth Adding to Your ~/.gitconfig.
When a workflow outgrows a one-line alias, write a script instead: any executable named git-<name> on your PATH runs as git <name>. git fix-dates is one example — a Bash script that restores commit dates after a rebase and force-pushes with a lease. git prune-branches is another — it deletes local branches that have already been merged, with a dry run, a confirmation prompt, and a restore command for each deletion. And git sync turns the stash–pull–rebase routine for keeping a feature branch current into a single command.
Separate Work and Personal Config with includeIf
Work and personal projects often need different identities: a different email address, a different signing key, sometimes different defaults. Rather than setting them in every repository, includeIf loads an extra config file only when a condition matches. Put it after the settings it overrides, because the last value Git reads wins.
# ~/.gitconfig
[user]
name = Your Name
email = you@example.com
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work# ~/.gitconfig-work
[user]
email = you@company.example
signingkey = ~/.ssh/id_ed25519_work.pubEvery repository under ~/work/ now commits as you@company.example, and everything else keeps your personal address. git config --show-origin user.email confirms which file a value came from:
file:/home/you/.gitconfig-work you@company.exampleRecovering From Disaster: git reflog
reflog is a local, private log of every place HEAD and each branch have pointed — it's what makes Git's "undo" commands feel so fearless, because almost nothing is actually gone until Git's garbage collector eventually runs.
git reflog # every place HEAD has pointed, most recent firsta1b2c3d HEAD@{0}: commit: Add validation
e4f5g6h HEAD@{1}: reset: moving to HEAD~1
h7i8j9k HEAD@{2}: commit: Fix typo
k1l2m3n HEAD@{3}: checkout: moving from main to feature/loginRecovering a commit that a reset --hard (or a bad rebase, or an accidental branch deletion) seemed to erase:
git reflog # find the SHA from just before the mistake
git branch recovered-work a1b2c3d # create a new branch pointing at it — nothing is lost
# or, to put your CURRENT branch back exactly where it was:
git reset --hard a1b2c3dCommon Workflows
The commands above compose into a handful of well-known branching strategies. None is "correct" — the right one depends on release cadence and team size.
| Workflow | Shape | Best fit |
|---|---|---|
| GitHub Flow | main is always deployable; every change is a short-lived feature branch + PR, merged straight back into main | Continuous deployment, web apps |
| Git Flow | Long-lived main + develop, with feature/*, release/*, and hotfix/* branches | Scheduled releases, versioned software |
| Trunk-Based Development | Everyone commits small, frequent changes directly to main (or very short-lived branches), often behind feature flags | Large teams, high commit velocity, strong CI |
GitHub Flow
Git Flow
Trunk-Based Development
Squash and rebase merges have a side effect locally: they create new commits on main, so git branch --merged and git branch -d no longer recognise your feature branches as merged, and they pile up. git prune-branches detects both kinds by comparing patches instead of commit hashes, and deletes them safely.
All three workflows assume a shared remote. When there isn't one, such as on an air-gapped build machine, in a project that takes patches by email, or for a client who wants a release as a zip file, Share Git Commits Without a Remote: format-patch, bundle and archive shows how to move work without one.
Performance: Shallow, Sparse & Partial Clones
Once a repository gets large — long history, huge tree, or both — a few flags keep everyday work fast.
git clone --depth 1 <url> # shallow: only the latest commit's history
git clone --filter=blob:none <url> # partial: full commit history, file content fetched on demand
git sparse-checkout init --cone # sparse: only materialize specific directories on disk
git sparse-checkout set src/ docs/
git gc # compact loose objects into packfiles, prune unreachable ones
git maintenance start # schedule background gc/prefetch automaticallyCommand Cheat Sheet
A quick-reference pass over this post's topics.
| Task | Command |
|---|---|
| Rebase onto main | git rebase main |
| Interactive rebase | git rebase -i HEAD~n |
| Autosquash a fixup | git commit --fixup=<sha> + git rebase -i --autosquash main |
| Compare a branch before and after a rebase | git range-diff main @{1} HEAD |
| Rebase a stack of branches together | git rebase --update-refs main |
| Test every commit during a rebase | git rebase -x "npm test" main |
| Apply one commit elsewhere | git cherry-pick <sha> |
| Let one side win conflicting hunks | git merge -X ours <branch> |
| Find a bug's origin | git bisect start |
| Remove a file from all history | git filter-repo --path <file> --invert-paths |
| Add a submodule | git submodule add <url> <path> |
| Work on two branches at once | git worktree add <path> <branch> |
| Inspect any object | git cat-file -p <sha> |
| Sign a commit / a tag | git commit -S / git tag -s <tag> |
| Use a config file only in some folders | [includeIf "gitdir:~/work/"] |
| Recover "lost" work | git reflog |
| Shallow / partial clone | git clone --depth 1 / --filter=blob:none |
Best Practices
Never force-push to a shared branch without warning. If a rewrite is truly necessary, use --force-with-lease (it fails safely if the remote has commits you haven't seen yet, instead of silently discarding them), and tell whoever else has that branch checked out.
git push --force-with-leaseReach for git reflog before you panic. Almost nothing committed is truly lost immediately — reflog, fsck --lost-found, and the object store itself usually have your back.
Prefer git filter-repo over git filter-branch. It's the tool Git's own docs point to now for history-wide rewrites — faster, and much harder to get subtly wrong.
Keep hooks fast, or people will bypass them. A pre-commit hook that takes 30 seconds trains everyone to reach for --no-verify, which quietly defeats the whole point. Keep it fast, or move the slow checks to CI instead.
Squash before you share, not after. Interactive rebase to clean up a branch's commits is cheap and safe before anyone else has pulled it. Once it's shared, you're stuck merging instead — so tidy up early.
Common Pitfalls
"I need to undo a merge I already pushed"
git revert -m 1 <merge-commit-sha> # -m 1 keeps the mainline parent, undoing the merged-in side"My interactive rebase hit a conflict and I'm not sure what state I'm in"
git status # tells you exactly which commit is being replayed and what's conflicted
git rebase --abort # when in doubt, bail out entirely — you're back to before the rebase started"I force-pushed and think I overwrote someone's commits"
# On THEIR machine, if they still have the old commits checked out or in their own reflog:
git reflog # find the SHA of the commit that got overwritten
git push origin <that-sha>:main # push it back up, then reconcile properlyGoing forward, this is exactly the scenario --force-with-lease exists to prevent.
Frequently Asked Questions
Conclusion
Git's surface area is large, but nearly all of it comes back to the same handful of ideas from Part 1: commits are immutable snapshots, and branches are cheap, movable pointers into that snapshot history. Everything in this post is really just that model applied more forcefully — rebasing is replaying pointers onto a new base, reflog works because old pointer positions don't vanish immediately, and a "commit" is, underneath it all, just a tree object with a parent and a message.
Key Takeaways:
mergepreserves history as it happened;rebaserewrites it for linearity — never rebase commits others have already pulled- Interactive rebase (
rebase -i) is the single most useful tool for turning messy WIP commits into a clean, reviewable history before sharing it git reflogis your safety net — almost nothing is unrecoverable until garbage collection actually runs- Prefer
--force-with-leaseover--forcewhen a rewrite genuinely must be pushed - A commit is a tree + parent pointer(s) + metadata; a branch is a file containing a SHA — once that clicks, most "advanced" Git stops feeling like magic
- Pick a workflow (GitHub Flow, Git Flow, trunk-based) that matches your release cadence, and stay consistent about it as a team
Between this post and Part 1, you can go from your first git init to rewriting history with confidence. When a command's exact flags slip your mind, git help <command> is always one step closer than a search engine.
🔗 Up Next (Part 3): Searching Git History: git log -S, -L, git grep and git blame — where we'll cover:
- Finding when code was added, removed or changed with
git log -Sand-G - Following one function through history with
git log -L - Tracking down deleted and renamed files with
--diff-filterand--follow - Searching any commit with
git grep, and getting honest answers fromgit blame
This part is the one that turns Git from "a tool I follow instructions for" into something you can actually reason about — I hope the internals section in particular makes the rest of it click. Part 3 puts that model to work searching history, so you can find out exactly when, how and by whom any line changed. 🚀