Git rebasing allows developers to clean up, reorganize, or modify commits before integrating them into a main branch. This guide will explain how to edit individual commits using interactive rebase, which provides a flexible interface for making changes to your commit history during rebase operations.
Understanding Git rebasing
Git rebasing allows you to modify the base of your branch from one commit to another, effectively moving or copying your commits. This process can be used to change commit messages, edit the content of commits, reorder commits, and more. It is particularly useful for maintaining a clean and logical commit history in a collaborative project.
Interactive Git rebasing
To start an interactive rebase, use the following command:
git rebase -i HEAD~N
Replace N
with the number of commits you want to review. For example, HEAD~3
will include the last three commits in the rebase process.
The interactive rebase todo list
When you initiate an interactive rebase, Git opens a todo list in your default text editor. This list shows recent commits from oldest (top) to newest (bottom) and allows you to choose an action for each commit:
- pick: use the commit
- reword: use the commit, but edit the commit message
- edit: use the commit, but stop to amend the commit content or message
- squash: merge this commit into the previous commit, combining their messages
- fixup: merge this commit into the previous one but discard this commit's log message
- drop: remove the commit
Editing commits
To edit a commit:
Change the command from
pick
toedit
next to the commit you want to alter, then save and close the editor. Git will pause the rebase at that commit, allowing you to make changes.Make your desired changes to the working directory. This could involve editing files, adding new files, or removing files.
Stage the changes by running:
Terminalgit add <file1> <file2> <fileN>Make sure to replace the placeholder filenames with the actual names of the files you are editing.
Amend the commit by using:
Terminalgit commit --amendThis opens your editor to modify the commit message if necessary. Save and close the editor after making any changes to the commit message.
Continue the rebase by using:
Terminalgit rebase --continueRepeat this process for each commit you marked for editing. If at any point you need to stop and exit the rebase process, you can use
git rebase --abort
to revert to the original state of your branch.
Rewording commits
If you only need to change commit messages, use the reword
option instead of edit
. This will pause the rebase at each selected commit, allowing you to change the commit message without altering the content of the commit.
Changing commit order
To change the order of commits, simply rearrange the lines in your todo list editor. Be cautious with this as changing the order can cause conflicts if later commits depend on earlier ones.
For further reading, see the official Git documentation.