DEV Community

Cover image for Git basics: Changing your last commit message
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Git basics: Changing your last commit message

You might accidentally make a typo while writing your commit message.
Or because you quickly tried to solve a bug, you accidentally left the old commit message and pushed that.

It's a good practice to keep the message meaningful, so you'll know what you change in which commit.

I made a wrong commit message on my GitHub repo to showcase how it works.

Wrong git commit message

In the image above, we see I committed some changes with the message: "fix: image name wrong message".

Let's see how we can fix that.

Fixing a non-pushed commit message

If you haven't pushed your code yet, it's easier to fix.

You can run the following command.

git commit --amend
Enter fullscreen mode Exit fullscreen mode

This will open up a vim editor where you can change the commit's message.

Editing wrong commit message

To edit the text, press the i key, and to stop, press esc then wq to save the file.

However, a faster way is to use the -m property, which can be used to amend the commit message.

git commit --amend -m "fix: image name correct message."
Enter fullscreen mode Exit fullscreen mode

We can see the commit message altered without pushing a new commit.

Altered commit message

Fixing a pushed commit message

However, what happens if we already pushed the wrong message to GitHub, for instance.

Wrong commit message on GitHub

No worries, we can still fix it without messing things up.

If we are addressing the last commit, we can again run the following command:

git commit --amend -m "fix: image name"
Enter fullscreen mode Exit fullscreen mode

The next step is to push while overwriting the previous commit message.
For that to work, use the following command:

git push --force-with-lease origin your-branch

# in my case:

git push --force-with-lease origin master
Enter fullscreen mode Exit fullscreen mode

And that's it. We now changed the already pushed commit message.

Changes pushed commit message on GitHub

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (2)

Collapse
 
waylonwalker profile image
Waylon Walker

--amend FTW! such a great tool

Collapse
 
dailydevtips1 profile image
Chris Bongers

Yep! πŸ’–