How to Modify a Specific Commit in Git

John Wachira Feb 15, 2024
How to Modify a Specific Commit in Git

This article illustrates how we can modify a specific commit in Git. You may need to rename, squash, edit, or add files to a commit.

The best way to do this is to use the git rebase command in the interactive mode. How do you go about this?

Modify a Specific Commit in Git

To modify a commit, you must run a git rebase in interactive mode. Let’s use an example to demonstrate.

git log –oneline

We will run the command below to run a git rebase in an interactive mode.

$ git rebase -i HEAD~10

git rebase

As we can see, there are several commands we can use to modify the commits.

Let’s quickly go through the options.

  1. pick - We use it to reorder our commit history.
  2. reword - We use it when we want to change the commit message. It does not affect the changes introduced by the commit.
  3. edit - We use it when we want to edit or amend a commit. We can split a commit into smaller commits or remove errors introduced by the commit.
  4. squash - We use it to combine two commits into one, and it gives us a chance to give the new commit a new message.
  5. fixup - It is the same as squash except that it discards the message for the merged commit and uses the one above it.

To modify a commit, we will replace pick with any of the options above. Let’s try to rename one of our commits.

We will reword the 8c1cefc My Commit Message commit and squash the three code corrections.

Modify a commit

After editing, we can exit the text editor to complete the rebase. Git will open the text editor again to allow you to give our commit a new message.

Git will also open the editor once more to allow us to give our squashed commits a commit message.

At this point, you may encounter merge conflicts. You will have to manually resolve the conflicts and commit the changes.

To commit the changes, we will run the git commit with the --amend flag, as shown below.

$ git commit --amend --all --no-edit

The last step is finishing the rebase with the command below.

$ git rebase --continue

This will finish the rebase and modify the selected commits.

In a nutshell, we can modify commits in Git by running a rebase in interactive mode. There are several commands available in interactive mode to modify commits.

When committing changes, use the --amend flag.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Commit