You just committed that awesome feature, test, or bug fix, but something isn’t quite right. Maybe some information is missing, the commit message is incorrect, or something else is off. Let’s go over what can be done to fix the associated data after the fact.

Fixing the Previous Commit

Fixing the previous commit is very simple. Just use:

git commit --amend

This will open the commit message in your default editor. Simply edit the message on the top line of the file, save, and quit. That’s it!

Fixing Multiple Commits or Older Commits

If you need to fix a few commits, or if the broken commit is a few commits back, the process is a bit more complex but still manageable. Here’s how you can do it:

Step 1: Generate Patch Files

Assume the last three commits have the wrong username, email, or commit message. Start by generating patch files for these commits:

git format-patch HEAD^^^

This command will generate files named 0001-commit-message, 0002-commit-message, and so on, containing the commit diffs and metadata. Note: The three caret symbols (^^^) indicate how many commits back you want to go. You can also use the syntax HEAD~3 to refer to the last three commits.

Step 2: Edit the Patch Files

Open each patch file and edit the information to correct the commit messages or other details.

Step 3: Reset the Repository

Reset your repository back a few commits:


git reset --hard HEAD^^^

This will move your repository state back to where it was three commits ago.

Step 4: Apply the Corrected Commits

Now apply each corrected commit in the right order:

git am < 0001-commit-message.patch
git am < 0002-commit-message.patch
git am < 0003-commit-message.patch

Step 5: Verify the Changes

Check the commit log to ensure the correct information is now present:

git log

Step 6: Force Push the Changes

If everything looks correct, you will need to force push the changes to the remote repository:

git push -f

The -f (force) flag is necessary because you are rewriting commit history. Be aware that modifying commit messages in this way can affect others who have pulled the repository. Use this with caution, as it may cause issues for other developers.

Rollback if Necessary

If something goes wrong, you can always reset back to the original state:

git reset --hard origin/master

This will restore the repository to the state of the last commit on the remote master branch.

Fixing commit messages after the fact is possible but should be done carefully, especially when it involves rewriting history. Always communicate with your team before making such changes to avoid disruptions. If you have any additional tips or questions about potential consequences, feel free to share them in the comments. Future tips will cover fixing actual committed files and ensuring all repositories are up to date.