If you make a mistake with a commit and need to make changes or you'd like to update the commit message of the most recent comment, you can do this with the
git commit --amend command.
We have some changes to commit here. We'll just run git commit -m and then we'll provide a commit message. Once we let the git hooks run, we'll see that our commit succeeded. Now if we look at the git status we'll notice that we made a mistake. We didn't add all the files we meant to.
There are various ways to fix this. For this scenario we'll simply use the amend flag for the git commit command. First we'll run git add . to add all the files we want. Now let's double-check that we have all the files that we want with git status. It looks like we're good.
Now we'll run git commit amend and because this project has a git hook for a commit message we're going to see that run before anything else happens. Once that's done our default editor for git will come up, allowing us to change the commit message and we'll also see the files that will be associated with this commit.
Looks like we're good. Let's save and close the file. Now if we run git status we'll see that we have nothing else to commit, and if we run git log we'll see that the most recent commit is the one we just executed. The amend flag can also be used to change the most recent commit message. Let's go ahead and try that.
Even though we have nothing staged, if we run git commit --amend, again, it will execute the commit message git hooks, but then we'll see that we can still change the commit message here. Let's add an emoji just for fun. Now we'll save and close the file.
Now if we run git log we'll see our new commit message. It looks like git log doesn't like emoji very much. You need to remember that this is changing commit history and as always if you're changing anything that's already been pushed to a remote repository, you'll have to force push to alter the history on the remote repository. Otherwise your push will be rejected.
Make sure that you know what you're doing before you do this. Also if you need to alter the message of an older commit, you can use the reword command in an interactive rebase, which is a whole another beast.