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

  1. Open the terminal: First, open your command-line terminal.
  2. Navigate to your Git repository: Use the cd command to move to the directory containing your Git repository.
  3. Execute the interactive rebase: Run the command git rebase -i HEAD~N, where N is the number of commits to rebase. For example, to interactively rebase the last 3 commits, use git rebase -i HEAD~3.
  4. Select operations: In the opened editor, you'll see a list of the most recent N commits, each prefixed with pick. Change pick to other commands to specify actions:
    • pick: Keep the commit
    • reword: Keep the commit content but modify the commit message
    • edit: Pause applying the commit to modify it directly
    • squash: Merge the commit with the previous one and combine commit messages
    • fixup: Merge the commit with the previous one but discard its commit message
    • drop: Remove the commit
  5. Save and exit: After editing, save and close the editor. Git will apply the specified operations to each commit.
  6. 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 --continue to proceed.
  7. 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:

shell
pick 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:

shell
pick 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.

标签:Git