1. Home
  2. Blog
  3. DevOps

DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step

To squash commits in Git, combine several small commits into one with interactive rebase, reset –soft, merge –squash or fixup commits with autosquash. Here is each method with before-and-after logs we ran on Git 2.56, plus how to push safely and undo a squash.

8 min read
Git squash commits: 4 easy ways

Key takeaways

  • To git squash commits, there is no git squash command; you squash with rebase -i, reset --soft, merge --squash or --fixup plus --autosquash.
  • In our test, four commits became one and git diff against a backup branch was empty: squashing changes history, not code.
  • Squashing rewrites commits, so after pushing you need git push --force-with-lease, and only on your own branches.
  • A bad squash is easy to undo with git reflog or a backup branch made beforehand.

A feature branch often ends up looking like “Add login form”, “Fix typo”, “WIP”, “Address review comments”. Those commits helped while you worked, but they make the main branch history noisy and harder to search, revert or bisect. Learning to git squash commits lets you hand over one clean, meaningful commit instead. We ran every command below on Git 2.56 in a throwaway repository with a demo identity.

What does squashing mean?

Squashing combines several commits into a single new commit that contains all their changes. The file content at the end is identical; only the history is shorter. Because the squashed commit is new, it gets a new hash, which is why squashing counts as rewriting history, like a rebase. If rebase itself is unfamiliar, read our git merge vs rebase guide first.

Our messy branch

$ git log --oneline
53525d2 Address review comments
269f98a WIP
ec1ea71 Fix typo
362d7e9 Add login form
893db6f Initial commit

The goal: turn the top four commits into one called “Add login form with validation”. Before any history rewrite, make a safety net:

git branch backup-feature

Method 1: interactive rebase (most flexible)

git rebase -i HEAD~4

Git opens an editor listing the last four commits, oldest first. Keep the first as pick and change the others to squash (or s):

pick 362d7e9 Add login form
squash ec1ea71 Fix typo
squash 269f98a WIP
squash 53525d2 Address review comments

Save and close. Git opens a second editor with all four messages combined; replace them with one good message and save. Our result:

Successfully rebased and updated refs/heads/feature/login.
$ git log --oneline
08989b9 Add login form with validation
893db6f Initial commit
$ git diff backup-feature --stat
(no output)

The empty diff proves the code is exactly the same. Use fixup (f) instead of squash to throw away a commit’s message automatically, which is ideal for “Fix typo” and “WIP”. Interactive rebase also lets you reorder, edit or drop commits in the same pass, which makes it the most flexible option. In scripts, we set GIT_SEQUENCE_EDITOR and GIT_EDITOR to automate the editors; normally you just edit by hand.

Tip: if you do not know how many commits to count, use the branch point instead: git rebase -i $(git merge-base HEAD main) lists every commit on your branch.

Method 2: reset –soft (fastest)

git reset --soft HEAD~4
git commit -m "Add login form with validation"
$ git log --oneline
9138307 Add login form with validation
893db6f Initial commit

reset --soft moves the branch pointer back four commits but keeps every change staged, so a single commit captures them all. Again, the diff against the backup was empty. It is the quickest way to squash everything on a branch into one commit, with no editor involved. It cannot keep some commits separate; for that, use interactive rebase. Our git reset vs revert guide explains --soft, --mixed and --hard.

Method 3: merge –squash (squash while merging)

git switch main
git merge --squash backup-feature
git commit -m "Add login form (squashed)"
Squash commit -- not updating HEAD
 app.txt | 4 ++++
$ git status --short
M  app.txt
$ git log --oneline --graph
* d114bb0 Add login form (squashed)
* 893db6f Initial commit

Git applied all the branch changes to main and staged them, but did not commit, which is why we committed ourselves. The feature branch is left untouched. This is what the “Squash and merge” button does on GitHub and GitLab. One catch: because main does not record a real merge, Git will not know the branch was merged, so delete it afterwards to avoid merging it twice.

Method 4: fixup commits and autosquash (cleanest habit)

If you already know a new change belongs to an earlier commit, mark it at commit time:

git commit --fixup HEAD~1
$ git log --oneline -4
130a78e fixup! Add logout button
0228579 Change colour
1bc8545 Add logout button

Later, one command folds every fixup into its target, even with other commits in between:

GIT_SEQUENCE_EDITOR=true git rebase -i --autosquash HEAD~3
$ git log --oneline -3
4edf05c Change colour
a207434 Add logout button
d114bb0 Add login form (squashed)

The fixup disappeared into “Add logout button”, and the file contained the corrected content. Setting GIT_SEQUENCE_EDITOR=true accepts the generated plan without opening an editor. On our first attempt the fixup changed the same lines as the commit in between, so Git stopped with a conflict. Fixups move commits around, so conflicts are possible; resolve them, or run git rebase --abort to return to where you started.

Which squash method should you use?

Method Best for Keeps some commits? Editor needed
rebase -i Cleaning a branch carefully Yes Yes
reset --soft Squashing everything quickly No No
merge --squash Squashing at merge time No No
--fixup + --autosquash Planned fixes during review Yes No (optional)

Pushing a squashed branch

If the commits were already pushed, the remote still has the old ones and a normal push is rejected. Use:

git push --force-with-lease

--force-with-lease refuses to overwrite the remote if someone else pushed in the meantime, unlike plain --force. Only do this on branches that you alone work on. Your CI pipeline will run again on the new commit, as described in our GitHub Actions CI/CD guide.

How to undo a squash

Old commits are not deleted immediately. The reflog records where the branch pointed before:

$ git reflog -4 feature/login
08989b9 feature/login@{0}: rebase (finish): refs/heads/feature/login onto 893db6f
53525d2 feature/login@{1}: commit: Address review comments
269f98a feature/login@{2}: commit: WIP
ec1ea71 feature/login@{3}: commit: Fix typo

To go back, run git reset --hard feature/login@{1} (or the hash 53525d2). Our backup branch also still pointed at 53525d2, which is the simplest undo of all. For bringing back a single commit instead, see our git cherry-pick guide.

Writing a good squashed commit message

A squash is your chance to replace “WIP” and “Fix typo” with a message that will still make sense in a year. A simple template works well:

Add login form with validation

- Email and password fields with client-side checks
- Shows a clear error for wrong credentials
- Rate-limits repeated failed attempts

Refs: TICKET-142

Keep the first line under about 50 characters and written as a command (“Add”, “Fix”, “Remove”). Leave a blank line, then explain what changed and why in short bullets, and link the ticket. Tools such as git log --oneline, release notes and semantic versioning changelogs read that first line, so make it count.

Squash locally or with the merge button?

GitHub, GitLab and Bitbucket all offer “squash and merge” on pull requests. It produces the same single commit as merge --squash, with no local commands and no force-push. Squash locally instead when you want to keep a few logical commits rather than one, or when reviewers should see a clean history before merging. Many teams do both: tidy with fixups during review, then squash-merge at the end.

When not to squash

  • Shared branches: rewriting commits others have pulled causes confusing conflicts.
  • Meaningful steps: a refactor and a feature are easier to review and revert as separate commits.
  • Huge squashes: one 3,000-line commit hides what changed and makes git bisect less precise.
  • Team rules: some teams prefer merge commits that keep full history. Agree on one approach.

Final thoughts

When you git squash commits, you trade noisy history for a readable one without changing a single line of code. Use interactive rebase for careful clean-ups, reset --soft for a quick “make it one commit”, merge --squash or your platform’s squash button at merge time, and fixup commits as a daily habit. Make a backup branch first, push with --force-with-lease, and remember the reflog if anything goes wrong. Keep our Git commands cheat sheet close for the rest.

Frequently asked questions

How do I squash the last 3 commits in Git?

Run git rebase -i HEAD~3, change pick to squash on the second and third lines, save, and write one commit message. Or run git reset –soft HEAD~3 followed by git commit.

What is the difference between squash and fixup?

Both combine a commit into the one above it during an interactive rebase. squash lets you edit the combined message, while fixup discards the squashed commit message.

Does squashing commits change my code?

No. The final files are identical; only the commit history changes. In our test, a diff between the squashed branch and a backup of the original branch was empty.

Can I squash commits after pushing?

Yes, but you must update the remote with git push –force-with-lease, and you should only do it on branches nobody else is using.

How do I undo a git squash?

Use git reflog to find the commit the branch pointed to before the squash, then git reset –hard to that entry, or reset to a backup branch you created first.

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

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 →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

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 →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →