Skip to main content

Harshal V. LADHE

Advanced Git: Rebasing, Internals, and Real-World Workflows

Rebase confidently, understand internals, and recover from anywhere.
Published at:
Last updated:
Estimated reading time:21 min read
Series:Git: From Basics to Advanced (2/3)
Advanced Git: Rebasing, Internals, and Real-World Workflows — a dark neon Git-themed infographic with panels showing git range-diff comparing old and new commits after a rebase, merge -X ours and theirs resolving a MAX_ATTEMPTS conflict, SSH commit and tag signing with a verified signature, and an includeIf ~/.gitconfig switching identity between ~/code and ~/work, alongside topic tiles for rebasing, cherry-pick and bisect, internals, worktrees, hooks and reflog recovery, plus a terminal of powerful commands.(opens full-size image in a new tab)
Rebasing with range-diff, merge -X strategies, commit signing, includeIf and reflog recovery.

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-pick and bisect for 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 main

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

Diagram of git rebase main on feature: before, feature branches off main at commit B with its own commits D and E; after, those commits are replayed as new commits D' and E' on top of main's latest commit C, rather than moved or merged in place.mainfeatureABCDEgit rebase mainreplays D, E as new commits D', E'mainfeatureABCD'E'original commitreplayed commit

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 main

This 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 you

The 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 option

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

Diagram of git range-diff pairing the old version of feature/login with the rebased one: Add login form and Add validation are unchanged (=); Add debug logging exists only in the old version (<); Add rate limiting was changed (!) and moved from position 4 to 3; and Add remember-me option exists only in the new version (>).feature@{1} (before)feature (after)1: Add login form1: Add login form=2: Add validation2: Add validation=3: Add debug logging<4: Add rate limiting3: Add rate limiting!4: Add remember-me option>=unchanged!changed<only in old>only in new

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 rebase

In 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 client

Branches 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 list

When 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 --continue

Fix 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 entirely

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

cherry-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:

CommandWhat it does
git merge -X ours featureA real merge: takes every non-conflicting change from feature, and resolves only the conflicting hunks in favour of your branch
git merge -s ours featureA different strategy: records a merge commit but keeps your tree exactly as it is, discarding all of feature's changes
git checkout --ours file.txtUsed 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 branch
Diagram of git bisect narrowing 8 commits down to the first bad one over 3 rounds: testing commit 4 (bad) narrows the range to 1-4, testing commit 3 (good) narrows it to 3-4, and since those are adjacent, commit 4 is confirmed as the first bad commit.1234test5678commit 4 is bad — search narrows to 1–4123test45678commit 3 is good — search narrows to 3–412345678commit 4 is the first bad commitgoodtestingbad

Bisect 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 history

Its 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 submodule

Subtrees

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 main

Worktrees

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 up

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

ObjectContains
blobA single file's raw content (no filename, no metadata)
treeA directory listing — names + modes, pointing at blobs and other trees
commitA pointer to one tree (the snapshot), one or more parent commits, author/committer, and a message
tagAn annotated tag's metadata, pointing at a commit

Here's how those objects actually link together for a small project:

Diagram of a Git commit pointing at its root tree, which points at a blob for index.js, a blob for styles.css, and a nested tree for src/, which itself points at a blob for utils.js.committreeblob (index.js)blob (styles.css)tree (src/)blob (utils.js)committreeblob

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 default

Hooks

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 suite

A 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 default

Despite 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 tag

To 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 tag
commit 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 limiting

For 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 --all

For 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.pub

Every 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.example

Recovering 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 first
a1b2c3d 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/login

Recovering 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 a1b2c3d

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

WorkflowShapeBest fit
GitHub Flowmain is always deployable; every change is a short-lived feature branch + PR, merged straight back into mainContinuous deployment, web apps
Git FlowLong-lived main + develop, with feature/*, release/*, and hotfix/* branchesScheduled releases, versioned software
Trunk-Based DevelopmentEveryone commits small, frequent changes directly to main (or very short-lived branches), often behind feature flagsLarge teams, high commit velocity, strong CI

GitHub Flow

Diagram of GitHub Flow: a short-lived feature branch forks off main, gets its own commits, and merges back into main via a single merge commit.mainfeatureABEFCDbranch, commit, open a PR, merge back into maincommitmerge commit

Git Flow

Diagram of Git Flow: main and develop are two long-lived lines. A feature branch forks off develop and merges back into develop. A release branch forks off develop and merges into both develop and main. A hotfix branch forks off main and merges into both main and develop.maindevelopfeaturereleasehotfixrelease and hotfix merge into both main and developcommitmerge commit

Trunk-Based Development

Diagram of Trunk-Based Development: commits land directly on a single main line, one after another, with no long-lived branches.maincommits land directly on main, multiple times a day

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 automatically

Command Cheat Sheet

A quick-reference pass over this post's topics.

TaskCommand
Rebase onto maingit rebase main
Interactive rebasegit rebase -i HEAD~n
Autosquash a fixupgit commit --fixup=<sha> + git rebase -i --autosquash main
Compare a branch before and after a rebasegit range-diff main @{1} HEAD
Rebase a stack of branches togethergit rebase --update-refs main
Test every commit during a rebasegit rebase -x "npm test" main
Apply one commit elsewheregit cherry-pick <sha>
Let one side win conflicting hunksgit merge -X ours <branch>
Find a bug's origingit bisect start
Remove a file from all historygit filter-repo --path <file> --invert-paths
Add a submodulegit submodule add <url> <path>
Work on two branches at oncegit worktree add <path> <branch>
Inspect any objectgit cat-file -p <sha>
Sign a commit / a taggit commit -S / git tag -s <tag>
Use a config file only in some folders[includeIf "gitdir:~/work/"]
Recover "lost" workgit reflog
Shallow / partial clonegit 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-lease

Reach 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 properly

Going 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:

  • merge preserves history as it happened; rebase rewrites 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 reflog is your safety net — almost nothing is unrecoverable until garbage collection actually runs
  • Prefer --force-with-lease over --force when 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 -S and -G
  • Following one function through history with git log -L
  • Tracking down deleted and renamed files with --diff-filter and --follow
  • Searching any commit with git grep, and getting honest answers from git 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. 🚀

Changelog

  • — Added cross-reference to tutorial 'Share Git Commits Without a Remote: `format-patch`, `bundle` and `archive`'
  • — Added sections on `git range-diff`, `rebase --update-refs`, `rebase --exec`, merge strategy options, conditional includes and commit signing
  • — Added cross-reference to snippet '`git sync`: Update Your Branch from `main` in One Command'
  • — Added cross-reference to snippet '`git prune-branches`: Delete Merged and Squash-Merged Branches'
  • — Added cross-reference to snippet 'Git Aliases Worth Adding to Your `~/.gitconfig`'
  • — Added cross-reference to snippet '`git fix-dates`: Fix GitHub Commit Dates After a Rebase'
  • — Initial publication
This post is licensed under CC BY 4.0 by the author.

Share this post

Spotted a mistake or something outdated in this post? Suggest a correction.

  • Git Basics: A Beginner's Guide to Version Control

    Master Git's core workflow, from commit to merge.
    A beginner-friendly guide to Git covering setup, the staging area, everyday commands like add/commit/diff/log, .gitignore, branching, merging, undoing mistakes, stashing, remotes, and tags.
    Published at:
  • Searching Git History: git log -S, -L, git grep and git blame

    Find when, why and by whom code changed.
    Find when code changed with git log -S and -G, trace a function with git log -L, search any commit with git grep, and blame past moves and reformats.
    Published at:
  • CSS Cascade Layers (@layer): End Specificity Wars in Large Codebases

    Control CSS priority with layer order, not specificity.
    Learn how CSS cascade layers (@layer) set priority by layer order instead of specificity — unlayered styles, the !important reversal, revert-layer, layering third-party CSS, the full cascade sort order, migrating a large codebase and putting utility classes last.
    Published at: