How to Change Last Commit in Git
This happens to me if I commit, then run tests or code formatter. Or sometimes
I forgot to add some files since I don’t use usual git add .
command. I rather
to add files one by one explicitly.
So how can we change the history? The last commit history?
Add File(s)
You forgot to add a file, or files into your commit and you want to add them. It is easy:
$ git add <your_forgotten_file>
# or add all files
$ git add .
$ git commit --amend --no-edit
If you want to change your commit message as well:
$ git commit --amend
This will open your last commit with your editor of choice for git:
$ git config --list
core.editor = nvim
Edit this commit message and then save it.
Change Commit Message
As shown above; if you just want to change your most recent commit message, just run:
$ git commit --amend
Or in one line:
$ git commit --amend -m <new_commit_message>
Now your last commit contains that change!
Warning
You should never amend commits that have been pushed up to a “public” branch! Only amend commits that only exist in your “local” or notice people about this change.
All done!