A quick post on how git amend command can help you fix and change your last commit if you want to add something more or have made a mistake.
Photo by Jelleke Vanooteghem on Unsplash
A mistake
First, a little bit of context, Let’s say you are starting a new Kotlin project with Gradle. The first usual thing to do is to check in a .gitignore
file with directives to ignore certain IDE generated files.
I wanted to ignore any temporary files generated by Gradle which are typically situated in .gradle
folder among the IDE files generated by IntelliJ in .idea
folder.
So I added below in the .gitignore
file:
gradle/
.idea/
And then went ahead with adding and committing my changes
git add .git commit -m "Ignore IDE files and gradle generated files"
Oops
However, when I checked my current files, I could still see a lot of the Gradle temporary files.
Turns out, Instead of adding .gradle
folder, I added gradle
(Notice the missing dot)
The fix
Well, A quick fix would be to just change the .gitignore
file and update to:
.gradle/
.idea/
And then add and commit with a new message right?
Well, That is how I used to do things before!
I wouldn’t ideally like to not show this trivial mistake in my git history when I can fix it. And why to necessarily clutter the git history with these small fixes.
Turns out Git has this awesome command that we can use.
In this particular case, I want to change the files that were checked in the last commit and maybe add some new files as well.
We can just stage any new files or change files that we need and execute below
git commit --amend --no-edit
This would modify your last commit files and retain the message
If you want to even change the message, Just add -m <msg>
to this command
git commit --amend -m "an updated commit message"
Conclusion:
Use git amend if you have made a mistake and fix your last commit. Note, This changes your last commit and it would not be recoverable.
Overall this is a very nice command to have in your git toolbox and allows you to have a better Git history.
The wonderful folks at Atlassian have written an even detailed blog on this. Check it out.
Top comments (1)
I always forget about --no-edit flag.