The Right Way to Squash Merge Master Branches

Abstract: Squash merge feature branches into master to clean up commit history and simplify reverting changes.

Created: 2026-09-11 by
Squash merging master branches in Git combines multiple commits into a single, clean history entry. This technique is essential for maintaining a linear repository structure and reducing clutter before integrating feature work into the main line of development. By using interactive rebasing or specific merge strategies, you can ensure that only the final state of your changes appears in the master branch.

Understanding Squash Merging

When developers work on feature branches, they often create numerous small commits to track their progress. These might include messages like "fix typo," "add debug log," or "update readme." While useful for individual tracking, these commits pollute the project history when merged into master. A squash merge collapses all these individual steps into one commit that represents the entire feature. This results in a cleaner git log, making it easier to understand what was changed and why during code reviews or audits. The primary benefit is readability. Instead of scrolling through fifty commits to find a significant change, reviewers see one commit with a comprehensive message. It also simplifies reverting changes; if a bug is introduced, you can revert the single squash commit rather than hunting down which specific intermediate commit caused the issue. However, this comes at the cost of losing the granular history of how the feature was built. You sacrifice the narrative of development for the clarity of the result.

Method 1: Interactive Rebase Before Merge

This approach is ideal when you want to clean up your branch locally before pushing it to the remote repository. It gives you full control over which commits are combined and allows you to edit commit messages easily. First, ensure your local master branch is up to date by running git pull origin master. Next, switch to your feature branch using git checkout feature-branch. To begin the interactive rebase, identify the base commit. Usually, this is the point where you branched off from master. You can find this by looking at the git log or using git merge-base HEAD master. Run the following command, replacing <base-commit> with the actual commit hash:
git rebase -i <base-commit>
This opens your default text editor with a list of commits. Each line starts with the word pick. To squash commits, change the word pick to s (or squash) for every commit you want to merge into the previous one. Keep pick for the very first commit in the list, as this will be the base for the new combined commit. Save and close the file. Git will then process the changes. If there are conflicts, resolve them and continue the rebase with git rebase --continue. Once complete, you will likely be prompted to edit the commit message for the new squashed commit. Write a clear, descriptive message that summarizes all the changes included. Finally, force push the updated branch to the remote repository using git push origin feature-branch --force-with-lease. The --force-with-lease flag is safer than --force as it prevents overwriting others' work if the remote branch has been updated since you last fetched.

Method 2: Using Merge with Squash Flag

If you prefer not to rewrite local history or deal with interactive editors, Git provides a direct merge option. This method creates a temporary merge commit that is immediately squashed, resulting in a single new commit on the target branch. Switch back to your master branch using git checkout master. Ensure it is up to date with git pull origin master. Then, execute the merge command with the --squash flag:
git merge --squash feature-branch
This command applies all the changes from feature-branch to your working directory but does not automatically create a commit. It stages all the changes as if you were about to commit them manually. Review the staged changes using git diff --cached to ensure everything looks correct. Once verified, commit the changes with a meaningful message:
git commit -m "Implement feature X: detailed description of changes"
Now, push the master branch to the remote repository:
git push origin master
This method leaves your local feature branch untouched, which can be convenient if you need to keep it for further experimentation. However, it does not clean up the history on the feature branch itself, so other developers pulling that branch later will still see the old, messy commit history. For team workflows, Method 1 is generally preferred because it cleans up the branch history globally.

Best Practices for Commit Messages

Regardless of the method used, the quality of your commit message is paramount. Since a squash merge condenses hours of work into one entry, the message must be self-contained. Follow the conventional commit format: start with a type prefix such as feat:, fix:, or docs:. Follow this with a concise summary of the change. Avoid vague phrases like "updates" or "changes." Instead, describe what the code now does. For example, use "feat: add user authentication API endpoint" rather than "auth stuff." Include details about breaking changes or migration steps if applicable. This practice helps future developers understand the context of the change without needing to read the diff entirely. It also aids in generating accurate changelogs automatically. For more information on managing repository cleanliness, you might find it helpful to look into How to Remove Old Screenshots from a Git Repository, which discusses similar hygiene practices. Additionally, understanding how to handle related version control tasks can streamline your workflow further. Check out How to Git Push to Origin Main: A Tech Support Guide for tips on safe remote updates.

Frequently Asked Questions

Does squash merge delete my original commits?

No, squash merging does not delete the original commits from your feature branch unless you use interactive rebase and force push. If you use the --squash merge flag, the original branch remains unchanged. Only the history on the target branch (master) is affected by the consolidation.

Can I recover a squashed commit if I made a mistake?

If you have already pushed the squashed commit to master, recovery is difficult because the history is rewritten. You would need to revert the squashed commit or cherry-pick the necessary changes onto a new branch. Always test your squash operations locally before pushing to shared branches to avoid irreversible data loss.

What is the difference between squash merge and rebase?

Squash merge combines all changes into one commit on the target branch, creating a flat history. Rebase moves your entire feature branch to the tip of master, replaying each commit individually. Squash merge hides the development process, while rebase preserves the individual steps but aligns them chronologically with master.

Is it safe to squash merge in a collaborative team?

It is safe only if you are the sole contributor to the branch. If multiple people are committing to the same feature branch, squashing will cause history conflicts for everyone else. In collaborative environments, use pull request features provided by platforms like GitHub or GitLab, which often support squash merging natively without requiring local rebasing.

Why should I avoid frequent squash merges?

Frequent squashing can hide important debugging information. If a bug is introduced in an early stage of feature development, having the granular history allows you to pinpoint exactly when the error occurred. Squashing erases this trail, making regression testing and root cause analysis significantly harder for future issues.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More