DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

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
Enter fullscreen mode Exit fullscreen mode

If you want to change your commit message as well:

$ git commit --amend
Enter fullscreen mode Exit fullscreen mode

This will open your last commit with your editor of choice for git:

$ git config --list

core.editor = nvim
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Or in one line:

$ git commit --amend -m <new_commit_message>
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)