How to Change Older or Multiple Commits

To change older or multiple commit messages, the git rebase command can be used to combine a series of commits into a new commit. The git rebase command alters the basis of the current branch from one commit to another and makes it look like the branch has been created from another commit. When it comes to keeping the project history clean, you should use the interactive rebase.

The interactive rebase mode allows stopping after each commit you want to alter, add files, and change the message.

  • Add the -i option to run the interactive mode. It will change the individual commits in the process:
    git rebase -i HEAD~n
  • You must indicate how far back you want to rewrite commits by instructing the git rebase command which commit to rebase onto. Here, the n is the number of recent files which commit message you want to amend. If you want to alter the last 2 pushed files, so you should run the following:
    git rebase -i HEAD~2

    Now you can move to the lines of the commit message and change it. After changing the message save and close the editor.

  • Then, force push the changes to the remote repository running the following:
git push --force branch-name

Multiple Messages

Each commit has a log message that explains what happened in the commit. During rebasing, a few commands on commits can be executed to amend commit messages:

  • Reword or r stops the rebase process and gives a chance to amend the commit message.
  • Squash or s combines two or more commits into a single commit. During the rebase process the commit is stopped and you are prompted to change the individual commit messages into a combined message.
  • Fixup or f is similar to squash. Unlike squash, fixup commits do not stop the rebase process to combine commit messages. The commit is merged into the commit above it, and the message of the earlier commit describes both changes.

Git launches your default text editor and opens a file with the details of the commits in the specified range, no matter which above command is used.

Git Rebase Standard and Git Rebase Interactive Modes

The git rebase command has two modes: standard and interactive. The standard mode automatically applies the commits in the current working branch to the passed branch head. The current branch will be rebased onto <base>. This can be different kinds of commit references, as a tag, an ID, a branch name, and so on. The interactive mode is carried out with the -i flag, which stands for “interactive”. The advantage of the interactive mode is altering the individual commits in the process, without moving all the commits to the new base. This mode cleans the history by removing and amending the existing sequence of commits.


Do you find this helpful?

Related articles