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

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

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

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 →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

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

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

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 →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

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