2024年7月4日 00:16
How to Interactively Rebase the Last N Commits in Git?
When using Git for version control, you may need to modify or adjust previous commits. Interactive rebase is a powerful feature that enables you to precisely modify or adjust your commit history.
Steps
- Open the terminal: First, open your command-line terminal.
- Navigate to your Git repository: Use the
cdcommand to move to the directory containing your Git repository. - Execute the interactive rebase: Run the command
git rebase -i HEAD~N, whereNis the number of commits to rebase. For example, to interactively rebase the last 3 commits, usegit rebase -i HEAD~3. - Select operations: In the opened editor, you'll see a list of the most recent N commits, each prefixed with
pick. Changepickto other commands to specify actions:pick: Keep the commitreword: Keep the commit content but modify the commit messageedit: Pause applying the commit to modify it directlysquash: Merge the commit with the previous one and combine commit messagesfixup: Merge the commit with the previous one but discard its commit messagedrop: Remove the commit
- Save and exit: After editing, save and close the editor. Git will apply the specified operations to each commit.
- Resolve potential conflicts: If conflicts occur during merging or applying commits, Git will pause and require you to resolve them. After resolving conflicts, use
git rebase --continueto proceed. - Complete the rebase: Once all commits have been reapplied, the rebase is complete.
Example
Suppose you have three recent commits and need to modify some of them:
bash$ git rebase -i HEAD~3
In the editor, you might see:
shellpick 12345a1 First commit message pick 67890b2 Second commit message pick abcde3f Third commit message
To modify the second commit's message and merge the third commit into the second, change it to:
shellpick 12345a1 First commit message reword 67890b2 Second commit message fixup abcde3f Third commit message
After saving and exiting the editor, Git will apply these changes.
This approach allows you to flexibly adjust your Git commit history to accommodate changes or enhance the clarity of your project history.