1. Home
  2. Blog
  3. DevOps

DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

git rebase interactive lets you rewrite a branch’s commits before you share them: combine wip commits, fix messages, reorder, drop or split. Learn every todo-list command, a full cleanup we ran step by step, autosquash, conflict handling and how to undo a rebase safely.

9 min read
Git rebase interactive: squash, fixup, reword and autosquash

Key takeaways

  • git rebase interactive (git rebase -i) replays your commits from a list you can edit: pick, reword, squash, fixup, drop and more.
  • Our five-commit messy branch became three clean commits, and git diff ORIG_HEAD HEAD showed the final files were identical.
  • git commit --fixup plus git rebase -i --autosquash automates most cleanups.
  • Only rewrite commits that nobody else has pulled. Use the reflog to undo a bad rebase.

Real work produces messy history: “wip”, “fix typo”, “oops”, “really fix it”. That is fine while you work, but a pull request with twelve noise commits is hard to review and harder to bisect later. Git rebase interactive is the tool for turning that history into a few clear, logical commits before you share it.

We ran every command in this guide with Git 2.56 in a throwaway repository, using a placeholder identity (Demo, demo@example.com) and fixed commit dates, and show the real output. Because interactive rebase normally opens an editor, we scripted the edits with GIT_SEQUENCE_EDITOR; the list you would edit by hand is identical. If rebasing itself is new, start with our merge vs rebase guide.

What is git rebase interactive?

A normal rebase takes your branch’s commits and replays them on top of another base. An interactive rebase does the same but first shows you the list of commits as a “todo” file. You change the command in front of each commit, reorder lines or delete them, save, and Git replays the commits according to your instructions, creating new commits with new hashes.

Starting an interactive rebase

git rebase -i main        # every commit on this branch since it left main
git rebase -i HEAD~5      # the last five commits
git rebase -i --root      # the whole history, including the first commit

The argument is the commit before the first one you want to change. HEAD~5 means “start after the commit five steps back”, so the last five commits appear in the list. Using the branch’s base, like main, is usually simplest for feature branches.

The todo-list commands

Command Short What it does
pick p Keep the commit as it is
reword r Keep the changes, edit the message
edit e Stop after this commit so you can amend or split it
squash s Meld into the previous commit and combine both messages
fixup f Meld into the previous commit and discard this message
drop d Remove the commit entirely
exec x Run a shell command, for example tests, at that point
break b Pause here; continue with git rebase --continue

Lines run from top to bottom, oldest commit first, which is the opposite of git log. squash and fixup always fold into the line above them.

Our messy feature branch

git log --oneline main..feature
8d69b14 Add discount
4ef2542 add tests
7045f60 fix typo in cart
08d7b87 wip
7a0c90c Add cart total

Five commits, newest first. “wip” and “fix typo in cart” are really part of “Add cart total”, and “add tests” deserves a better message. Running git rebase -i main showed this todo list (comments removed):

pick 7a0c90c # Add cart total
pick 08d7b87 # wip
pick 7045f60 # fix typo in cart
pick 4ef2542 # add tests
pick 8d69b14 # Add discount

Recent Git versions show the message after a # as a comment; only the command and hash matter.

Editing the todo list

pick 7a0c90c # Add cart total
fixup 08d7b87 # wip
fixup 7045f60 # fix typo in cart
reword 4ef2542 # add tests
pick 8d69b14 # Add discount

We changed two lines to fixup, so their changes fold into “Add cart total” and their messages vanish, and one line to reword. When Git reached the reword, it opened the editor for the message, where we wrote “Add tests for cart total”. Git reported its progress and finished:

Rebasing (2/5)Rebasing (3/5)Rebasing (4/5)[detached HEAD 808d176] Add tests for cart total
Rebasing (5/5)Successfully rebased and updated refs/heads/feature.

The result

git log --oneline main..feature
95b5c4d Add discount
808d176 Add tests for cart total
04fd1bb Add cart total

git diff ORIG_HEAD HEAD --stat
(no output: the final files are identical)

Three clear commits instead of five, and every hash changed because the commits were recreated. The empty diff against ORIG_HEAD, which Git sets to the pre-rebase tip, proves the end state of the code is exactly the same; only the history was reshaped. Run a git diff like this after any rebase you are unsure about.

squash vs fixup

Both combine a commit with the one above it. squash opens the editor with both messages so you can merge them into one; use it when the second commit’s message has useful detail. fixup keeps only the first message silently, which is what you want for “wip” and “typo” commits. Squashing a whole branch into one commit is covered in our git squash commits guide.

Tip: fixup -C in the todo list keeps the later commit’s message instead of the earlier one, handy when the follow-up commit has the better description.

Autosquash: let Git write the todo list

# fix something in the discount commit
git commit -a --fixup=HEAD
git log --oneline -2
9abb5d2 fixup! Add discount
95b5c4d Add discount

git rebase -i --autosquash main
git log --oneline main..feature
1d36fb4 Add discount
808d176 Add tests for cart total
04fd1bb Add cart total

--fixup=<commit> creates a commit whose message starts with fixup! plus the target’s subject. With --autosquash, Git moves it under its target and marks it fixup automatically, so you only need to save the list. We passed GIT_SEQUENCE_EDITOR=: to accept it without opening an editor. Set git config --global rebase.autoSquash true to make it the default, and use --squash=<commit> when you want to edit the combined message.

Reordering and dropping commits

To reorder, move lines up or down in the todo list. To delete a commit, change pick to drop or delete the line. Reordering is safe when commits touch different code; if a later commit depends on an earlier one, swapping them causes conflicts. Dropping a commit is a quick way to remove an experiment, but if you are not sure, prefer git revert on shared branches.

Using edit to amend or split a commit

# in the todo list
edit 7a0c90c # Add cart total

# Git stops after applying it:
git reset HEAD~1              # undo the commit, keep the changes
git add cart.py
git commit -m "Add cart total"
git add README.md
git commit -m "Document cart total"
git rebase --continue

This splits one oversized commit into two focused ones. You can also stop with edit just to change a file and run git commit --amend. We did not run the split sequence above in our demo repository; it follows the documented workflow.

Handling conflicts during a rebase

CONFLICT (content): Merge conflict in README.md
error: could not apply 99c8ad3... Rename heading

git status --short
UU README.md

We created this on purpose: both branches changed the same README line. Git paused on the commit that could not apply. Your options:

  • Fix the file, git add it, then git rebase --continue.
  • git rebase --skip to drop this commit and move on.
  • git rebase --abort to go back to exactly where you started, which is what we did.

Enable git config rerere.enabled true to let Git remember how you resolved a conflict and reuse it next time.

Undoing a rebase with the reflog

git reflog -n 3 --format='%h %gs'
95b5c4d rebase (finish): returning to refs/heads/feature
95b5c4d rebase (pick): Add discount
808d176 rebase (reword): Add tests for cart total

The reflog records every position HEAD has been in, including the state before the rebase. To undo a finished rebase, find the entry just before rebase (start), or use ORIG_HEAD right after the rebase, and run git reset --hard <that-hash>. Old commits stay recoverable for weeks by default, so a rebase is rarely a permanent mistake as long as you act before garbage collection.

The golden rule: do not rewrite shared history

Interactive rebase creates new commits. If others already pulled the old ones, their history and yours diverge, and they must untangle it. Rebase freely on your own feature branch before merging; never on main or a shared branch. If you already pushed your own branch, update it with git push --force-with-lease, which refuses to overwrite commits you have not seen, instead of a plain --force.

Git rebase interactive cheat sheet

Goal Command or todo action
Clean up a branch git rebase -i main
Merge wip into previous commit fixup
Combine messages squash
Fix a message reword
Change or split a commit edit
Remove a commit drop
Run tests at each step git rebase -i --exec "pytest" main
Prepare a fix for later squash git commit --fixup=<hash>
Bail out git rebase --abort
Undo after finishing git reset --hard ORIG_HEAD

More everyday commands are in our Git commands cheat sheet.

Final thoughts

Git rebase interactive turns the history you made while working into the history you want reviewers and future maintainers to read. Use fixup for noise, reword for messages, edit for splits, and autosquash to automate it all. Check the result with git diff ORIG_HEAD HEAD, keep the reflog in mind as your safety net, and only rewrite commits you have not shared.

Frequently asked questions

What does git rebase interactive do?

It shows the commits on your branch as an editable list. You choose to keep, reword, squash, fix up, edit, reorder or drop each one, and Git rebuilds the branch to match.

What is the difference between squash and fixup?

Both combine a commit with the one before it. Squash lets you edit a combined message from both commits, while fixup keeps only the earlier commit message and discards the other.

How do I undo an interactive rebase?

Right after the rebase, run git reset with the hard option and ORIG_HEAD. Later, find the pre-rebase commit in git reflog and reset to that hash.

How do I stop a rebase that has conflicts?

Run git rebase with the abort option to return to the state before the rebase began, or resolve the files, stage them and run git rebase with the continue option.

Is it safe to rebase commits that are already pushed?

Only on a branch nobody else uses. Rebasing creates new commits, so others who pulled the old ones will have conflicting history. Push the result with force with lease, not a plain force push.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
Software Development

HTTP Cookies Explained: Secure, HttpOnly, SameSite and Scope

HTTP cookies explained: Set-Cookie, Path, Domain, expiry, Secure, HttpOnly, SameSite, prefixes, deleting cookies and a secure session recipe, tested locally.

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Databases & SQL

SQL Auto Increment: MySQL, PostgreSQL, SQL Server and SQLite

SQL auto increment in MySQL, PostgreSQL, SQL Server and SQLite: syntax, reading the new ID, why gaps appear, ID reuse,…

Read article →
Databases & SQL

SQL BETWEEN: Inclusive Ranges and the Date Trap Explained

SQL BETWEEN explained with tested queries: inclusive ranges, reversed bounds, NULLs, the last-day date trap, half-open ranges and index-friendly date…

Read article →
Software Development

JavaScript Template Literals: 10 Examples Including Tagged Templates

JavaScript template literals explained with 10 tested examples: interpolation, multiline strings, escaping, tagged templates for safe HTML and SQL, and…

Read article →
Software Development

Python heapq: Priority Queues, Top N and Heaps Explained

Python heapq explained: heappush, heappop, heapify, priority queues with tie-breakers, max heaps, nlargest and merge, with real timings against sorting.

Read article →
Software Development

Python Walrus Operator (:=) Explained With 8 Real Examples

The Python walrus operator := explained with 8 tested examples: if checks, regex matches, while loops, comprehensions, scope rules, precedence…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →