Skip to content
$ lynuxpro
← Git

LESSON 13 OF 21 · ADVANCED · 20 MIN

Interactive rebase and rewriting history

HOW IT WORKSClean up commits before sharing

Add loginpickfix typofixupWIPsquashrebase -i todoedit the listAdd loginone clean commit
1/4

Real work produces messy commits: typos, WIP saves and fixes of fixes.

Real work produces messy commits: "WIP", "fix typo", "fix the fix", "address review comments". Before a branch is merged, it is good practice to tidy them into a few clear, meaningful commits that reviewers can follow and that are easy to revert later. Interactive rebase (git rebase -i) lets you edit your branch's history: squash commits together, reword messages, reorder, split or drop them. This lesson also covers autosquash, and removing secrets or large files from history.

The rule from the rebase lesson applies even more here: only rewrite commits that are not yet shared (or that live on your own feature branch).

In simple words

  • Interactive rebase: lets you edit a list of your recent commits: reorder, combine, rename or drop them before sharing.
  • Squash / fixup: join several small commits into one.
  • Force push: overwriting the branch on the server after rewriting history. Use --force-with-lease to avoid wiping others' work.
  • Rewriting history: changing commits that already exist. Fine on your own branch, risky on shared ones.

A messy branch

git config --global user.name "Leela Kumar"mkdir history-labcd history-labgit initprintf '# Shop\n' > README.mdgit add README.mdgit commit -m "Initial commit"git switch -c feature/loginprintf 'def login(user, pw):\n    return check(user, pw)\n' > auth.pygit add auth.pygit commit -m "Add login"printf 'def login(user, password):\n    return check(user, password)\n' > auth.pygit commit -am "fix typo"printf '\n\ndef logout(user):\n    pass\n' >> auth.pygit commit -am "WIP"printf 'Login: POST /login\n' >> README.mdgit commit -am "Document login"git log --oneline
SHELLbashutf-8 · 18L
6d1e2f3 (HEAD -> feature/login) Document login5c0d9e8 WIP4b9c8d7 fix typo3a8b7c6 Add login2f7a6b5 (main) Initial commit
OUTPUTterminalutf-8 · 5L

The goal: two clean commits, "Add login and logout" and "Document login endpoint".

Start an interactive rebase

git rebase -i BASE lets you edit every commit after BASE. Here, the four commits since main (equivalently HEAD~4):

git rebase -i main
SHELLbashutf-8 · 1L

Git opens your editor with a todo list, oldest commit first:

pick 3a8b7c6 Add loginpick 4b9c8d7 fix typopick 5c0d9e8 WIPpick 6d1e2f3 Document login# Commands:# p, pick <commit> = use commit# r, reword <commit> = use commit, but edit the commit message# e, edit <commit> = use commit, but stop for amending# s, squash <commit> = use commit, but meld into previous commit# f, fixup <commit> = like "squash" but keep only the previous commit's log message# d, drop <commit> = remove commit
OUTPUTterminalutf-8 · 12L

You edit the list, save and close the editor, and Git replays the commits following your instructions.

CommandEffect
pickkeep the commit as is
rewordkeep it, change its message
editstop after this commit so you can amend it or split it
squashmerge into the previous commit and combine both messages
fixupmerge into the previous commit, keeping only the previous message
drop (or delete the line)remove the commit
reorder linesreorder the commits

Squash, fixup and reword

Edit the plan so "fix typo" and "WIP" melt into "Add login", and the documentation commit gets a better message:

pick 3a8b7c6 Add loginfixup 4b9c8d7 fix typofixup 5c0d9e8 WIPreword 6d1e2f3 Document login
OUTPUTterminalutf-8 · 4L

The practice terminal has no editor, so it accepts the edited plan with a --todo option, using list positions (1 is the oldest commit) or hashes. The result is the same as saving the file in a real editor:

git rebase -i main --todo="pick 1; fixup 2; fixup 3; reword 4 Document login endpoint"git log --onelinegit show --stat HEAD~1
SHELLbashutf-8 · 3L
Successfully rebased and updated refs/heads/feature/login.8f3a2b1 (HEAD -> feature/login) Document login endpoint7e2b1c0 Add login2f7a6b5 (main) Initial commit
OUTPUTterminalutf-8 · 4L

Four noisy commits became two clear ones. With reword in a real terminal, Git opens the editor again for the new message. To also improve the first message you would amend it, or use reword on it too.

Autosquash: fix-ups without editing the list

When you know a change belongs to an earlier commit, create it as a fixup commit pointing at that commit:

git commit --fixup 7e2b1c0          # creates "fixup! Add login"git rebase -i --autosquash main     # the todo list is pre-arranged for you
SHELLbashutf-8 · 2L

With git config --global rebase.autoSquash true, every interactive rebase arranges fixup commits automatically. This is the cleanest way to address review comments.

Editing and splitting a commit

Mark a commit edit and the rebase stops right after it. You can then:

git commit --amend                  # change its content or message# or split it:git reset HEAD~1                    # undo the commit, keep the changesgit add auth.py && git commit -m "Add login"git add README.md && git commit -m "Document login"git rebase --continue
SHELLbashutf-8 · 6L

Squashing everything at merge time

GitLab and GitHub can squash a whole merge request into one commit when merging ("Squash commits" option). Many teams use that instead of manual squashing; interactive rebase is still the tool when you want a few well-structured commits rather than one.

After rewriting: force-push carefully

If the branch was already pushed, its history on the server no longer matches yours:

git push --force-with-lease
SHELLbashutf-8 · 1L

--force-with-lease refuses if someone else pushed to the branch in the meantime. Tell reviewers you rewrote the branch.

Removing secrets or huge files from history

git rm only removes a file from future commits. If a password or a 2 GB file was committed, it is still in history and in every clone. To rewrite the entire history, use git filter-repo (the modern, recommended tool; the old git filter-branch is deprecated):

pip install git-filter-repogit filter-repo --path secrets.env --invert-paths            # remove a file everywheregit filter-repo --replace-text expressions.txt               # replace leaked stringsgit push --force --all && git push --force --tags
SHELLbashutf-8 · 4L

This rewrites every commit hash after the first affected commit, so everyone must re-clone, and open merge requests must be re-created. Most importantly: rotating the leaked secret comes first. Removing it from history does not un-leak it.

When to rewrite and when not to

SituationRewrite?
Local commits not yet pushedyes, freely
Your own feature branch under reviewyes, then --force-with-lease
A branch others also commit toonly after agreeing with them
main, release branches, tagsno; use git revert
A leaked secret or huge fileyes, with filter-repo, coordinated with the whole team

Real-world scenario: a reviewable merge request

A merge request with 23 commits ("wip", "fix", "more fixes", "address comments x4") was impossible to review commit by commit, and when one change later needed reverting, it was spread across nine commits. The team adopted a habit: before requesting review, run git rebase -i main and shape the branch into logical commits ("Add rate limiter", "Use rate limiter in API", "Document rate limits"), and use --fixup plus autosquash for review comments. Reviews got faster, and reverts became one command.

Common mistakes

  • Rewriting shared history, then force-pushing over teammates' work.
  • Deleting a line in the todo list by accident, which drops that commit. If it happens, git rebase --abort (during) or git reflog (after) gets it back.
  • Using squash when you wanted fixup and ending up with a message full of "fix typo".
  • Thinking filter-repo makes a leaked secret safe. Rotate it.
  • Forgetting to re-run tests after reordering commits.

Practice

  1. Make four small commits on a branch, including two "fix typo" commits.
  2. Start git rebase -i and look at the todo list.
  3. Squash the typo fixes into the first commit using fixup (in the practice terminal, pass the plan with --todo).
  4. Reword the last commit's message.
  5. Check the result with git log --oneline and git show --stat.

Cheat sheet

git rebase -i BASE                 edit commits after BASE (e.g. main, HEAD~4)pick | reword | edit | squash | fixup | dropgit commit --fixup <commit>        mark a commit as a fix for anothergit rebase -i --autosquash BASE    arrange fixups automaticallygit config --global rebase.autoSquash truegit rebase --continue | --abortgit push --force-with-lease        after rewriting a pushed branchgit filter-repo --path FILE --invert-paths   remove a file from all history
OUTPUTterminalutf-8 · 8L

Key takeaways

  • Interactive rebase lets you squash, reword, reorder, edit and drop commits before sharing them.
  • fixup commits plus --autosquash are the cleanest way to address review comments.
  • Only rewrite unshared commits or your own branch; push with --force-with-lease.
  • git filter-repo removes files or secrets from all history, but rotating the secret comes first.
  • Clean history makes reviews, debugging and reverts much easier.