Git protip: fix last commit with "--amend"
By Maxime Bréhin • Published on 26 September 2022 • 2 min

Ah, carelessness, oversights and poorly written messages… All those situations where you created a commit only to realize that you screwed up!

Fortunately, the --amend option of the commit command is there to save you! 😮‍💨

Conceptually, Git will take one step back and one step forward for you. It will revert to the state it was in before committing (equivalent to git reset --soft HEAD~1), and will automatically commit again with all staged files (including the new ones, if you had added to the stage before running the --amend). Basically, it will undo your commit and create a new one instead, allowing / including intermediate changes:

  • adding / removing files;
  • updating metadata (usually the commit message).

By amending we dereference the current commit in favor of a new one, derived from it

The command is quite simple:

git commit --amend

Let’s look at the main use cases.

Adding a forgotten file

The most common case is forgetting to add a file to your commit, most of the time because it was untracked and you just went with the -a option that only adds already tracked / known files to Git: git commit -am '…'.

To fix this, you’ll have to:

  • add the file(s) to the stage: git add <les-chemins>;
  • cancel and replace the commit: git commit --amend.

Rewording the commit message

Let them who never made a typo or forgot an important reference like a ticket number in a commit message cast the first stone! Personally, I’m terrible at this.

When that happens, you’ll have to:

  • check that your stage is empty (you don’t want to add stuff to the updated commit);
  • run the git commit --amend command, possibly with the message “on the fly” if you want to rewrite it entirely (git commit --amend -m 'New message').

More tips and tricks?

We’ve got a whole bunch of existing articles and more to come. Also check out our 🔥 killer Git training course: 360° Git!

Would you like to go one step further and fully master Git core concepts, or to get advice on how to guarantee the quality of your Git projects? We can help or train you - just tell us what you need!