Interactive rebase is a powerful Git tool for cleaning up commit history before merging. 1) Use git rebase -i HEAD~n to rewrite the last n commits. 2) In the editor, replace 'pick' with commands like reword, squash, fixup, edit, or drop to modify commits. 3) Reorder lines to change commit sequence. 4) Save and follow Git’s prompts to complete the rebase. 5) Use git rebase --abort if errors occur. 6) After rebasing, push with git push --force-with-lease to safely update remote branches. Always rebase only local, unshared commits to avoid disrupting collaborators, ensuring a clean, logical, and maintainable project history.
Rewriting your Git history doesn’t have to be scary — when done right, interactive rebase is one of the most powerful tools for keeping your project history clean, logical, and easy to follow. Whether you're preparing a pull request or just tidying up local commits, git rebase -i
gives you full control over how your changes appear.

Here’s how to master it without breaking anything.
What Interactive Rebase Actually Does
At its core, git rebase -i
lets you rewrite, reorder, squash, edit, or remove commits in your branch before merging into main branches like main
or develop
. Unlike merge
, which preserves every step exactly as it happened, rebase lets you present your work more cleanly.

It’s ideal for:
- Combining small, incremental commits ("WIP", "fix typo", "forgot a file") into meaningful units
- Reordering commits so they tell a clearer story
- Rewriting commit messages for clarity
- Removing unnecessary or sensitive changes
Important: Only rebase commits that haven’t been pushed to shared branches. Once others have based work on your commits, rewriting history can cause confusion and conflicts.

How to Start an Interactive Rebase
Use this command to begin:
git rebase -i HEAD~n
Replace n
with the number of recent commits you want to modify.
For example, to clean up the last 4 commits:
git rebase -i HEAD~4
This opens your default text editor with a list of the 4 commits, looking something like:
pick abc1234 Add user login feature pick def5678 Fix login button alignment pick ghi9101 Refactor auth logic pick jkl2345 Update docs
Each line represents a commit, starting with the oldest. You can now choose what to do with each.
Common Commands in the Rebase Editor
You don’t just delete or move lines — you replace the word pick
with one of several commands:
reword
– Keep the changes but edit the commit messagesquash
– Combine this commit with the previous one (and edit the message)fixup
– Combine with the previous commit, discarding this commit’s message (great for merging "fix typo" commits)edit
– Pause during rebase to amend the commit (e.g., add forgotten files)drop
– Remove the commit entirely (or just delete the line)reorder
– Move lines around to change commit order
For example, turning this:
pick abc1234 Add user login feature pick def5678 Fix login button alignment pick ghi9101 Refactor auth logic
Into this:
pick abc1234 Add user login feature squash def5678 Fix login button alignment reword ghi9101 Refactor auth logic
…will merge the second commit into the first (with a chance to rewrite the combined message), and let you change the third commit’s message.
Save and close the file, and Git walks through your instructions step by step.
Practical Tips for Safer, Smarter Rebasing
Always pull the latest changes first
Make sure your branch is up to date with the base branch (e.g.,main
) before rebasing locally.Preview your changes with
git log
Rungit log --oneline
before starting to count the right number of commits and understand their order.Use
fixup
liberally for cleanup commits
If you have multiple “typo”, “l(fā)int”, or “forgot file” commits, mark them asfixup
to keep the history focused.Break large changes into logical chunks with
edit
If a commit does too much, useedit
to pause and split it:- During the rebase, when paused, use
git reset HEAD~1
to uncommit while keeping changes - Stage and commit parts separately
- Run
git rebase --continue
when done
- During the rebase, when paused, use
Abort if things go wrong
If you get lost, just run:git rebase --abort
This returns everything to how it was before the rebase.
After the Rebase: Push Carefully
If you’ve already pushed your branch, you’ll need to force-push after rebasing:
git push --force-with-lease
This is safer than --force
because it fails if someone else has pushed new commits to the same branch — preventing accidental overwrites.
Many teams use protected branches and require force-push permissions, so coordinate with your team before rewriting shared history.
Basically, interactive rebase is about presenting your work well, not changing what was done. Used wisely, it keeps your project history readable, professional, and maintainable.
Just remember: clean history is helpful, but not at the cost of collaboration. Rebase your own branches, not shared ones.
The above is the detailed content of Mastering Interactive Git Rebase for a Cleaner History. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Packfile is an efficient mechanism used by Git to package, compress and transfer repository objects. When you execute gitpush, gitfetch or gitclone, what Git actually transmits is the packfile; 1. It is initially generated by loose objects through gitgc or gitrepack commands and stored in the .git/objects/pack/ directory; 2. The packfile not only contains object data, but also records the delta relationship between objects, and achieves rapid search with index file (.idx). 3. This design reduces the transmission volume and improves synchronization efficiency; 4. A large number of small packfiles may affect performance, and can be used through gitgc or git

To view Git commit history, use the gitlog command. 1. The basic usage is gitlog, which can display the submission hash, author, date and submission information; 2. Use gitlog--oneline to obtain a concise view; 3. Filter by author or submission information through --author and --grep; 4. Add -p to view code changes, --stat to view change statistics; 5. Use --graph and --all to view branch history, or use visualization tools such as GitKraken and VSCode.

To delete a Git branch, first make sure it has been merged or no retention is required. Use gitbranch-d to delete the local merged branch. If you need to force delete unmerged branches, use the -D parameter. Remote branch deletion uses the gitpushorigin-deletebranch-name command, and can synchronize other people's local repositories through gitfetch-prune. 1. To delete the local branch, you need to confirm whether it has been merged; 2. To delete the remote branch, you need to use the --delete parameter; 3. After deletion, you should verify whether the branch is successfully removed; 4. Communicate with the team to avoid accidentally deleting shared branches; 5. Clean useless branches regularly to keep the warehouse clean.

ToswitchGitbranches,firstupdatethelocalrepowithgitfetch,checkexistingbrancheswithgitbranchcommands,thenusegitcheckoutorgitswitchtochangebranches,handlinguncommittedchangesbycommitting,stashing,ordiscardingthem.WhenswitchingGitbranches,ensureyourlocal

To discard the modifications in the Git working directory and return to the state of the last commit, 1. For the modifications of the tracked files, use gitcheckout-- or gitcheckout--. Discard all modifications; 2. For new files that are not tracked, use gitclean-f to delete the files. If the directory is included, use gitclean-fd. Before execution, use gitclean-fd to preview the delete content; 3. If you need to reset all changes (including the temporary storage area and the working directory), use gitreset-hard. This command will reset the working directory and the temporary storage area. Be sure to operate with caution. These methods can be used individually or in combination to achieve the purpose of cleaning up the working directory.

To add a subtree to a Git repository, first add the remote repository and get its history, then merge it into a subdirectory using the gitmerge and gitread-tree commands. The steps are as follows: 1. Use the gitremoteadd-f command to add a remote repository; 2. Run gitmerge-srecursive-no-commit to get branch content; 3. Use gitread-tree--prefix= to specify the directory to merge the project as a subtree; 4. Submit changes to complete the addition; 5. When updating, gitfetch first and repeat the merging and steps to submit the update. This method keeps the external project history complete and easy to maintain.

Git hooks are used to automatically run scripts before and after commits, pushes and other operations to execute tasks. Specific uses include: 1. Run code checks or tests before submission; 2. Forced submission information format; 3. Send notifications after push. They help unify team specifications and reduce manual steps, such as preventing submissions when tests fail. Git hooks are located in the .git/hooks/ directory in the repository and are not shared by default. They need to be copied manually or used tools such as Husky for team collaboration. Writing a basic hook requires creating an executable file and naming the corresponding event, such as pre-commit, and writing logical judgments there to block or allow operations.

Soundstageafafileiititwittingchatcase, USEGITIZEADTORDOREMEVOME FROMARNINGAREAILACT.TOUNDACT Rungit Reset.ForPartialStialing, Usgit rests-PtointelavEevstehuncificisshunissehunissue
