Git amend previous commit

Rewrit­ing com­mit his­tory with git

Pre­ma­ture com­mits hap­pen by acci­dent more often than not. Some­times you just missed adding a file or maybe you real­ized that you should have added a much more descrip­tive com­mit mes­sage. Either way, your intent is to edit your most recent com­mit. Thats where git commit --amend com­mand comes to your rescue.

There are two major use cases of  git commit --amend.

  • To edit just the pre­vi­ous com­mit mes­sage with­out chang­ing its snapshot.
  • To com­bine staged changes with the pre­vi­ous com­mit instead of com­mit­ting it as an entirely new snap­shot, with­out hav­ing to edit the com­mit message.

CAUTION : Never amend com­mits that have been shared with other devel­op­ers. Because, amend removes the pre­vi­ous com­mit (SHA) from the his­tory and cre­ates a new commit(SHA). So, if other peo­ple have based their work off that com­mit, it will be a con­fus­ing for them.


Edit a pre­vi­ous com­mit mes­sage in Git

The sim­ple com­mand is the following.

git commit --amend -m "your new message"

Below exam­ple, shows an exam­ple usage for it.


Com­bine staged changes with the pre­vi­ous com­mit with­out cre­at­ing a new snapshot

The sim­ple com­mand is the following.

git commit --amend --no-edit

Sup­pose, you added few files and com­mit­ted the change. Now, you real­ize you want to add one more file to that pre­vi­ous com­mit itself. Below exam­ple, demon­strates how to do it. Another, use case would be after com­mit­ting some­thing you real­ize you want to make some more changes and amend it to the pre­vi­ous com­mit instead of cre­at­ing a new snapshot.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *