Software Development Process

How To Edit Your Commits with `git commit --amend`

The git commit –amend command lets you modify your last commit. You can change your log message and the files that appear in the commit. The old commit is replaced with a new commit which means that when you amend your old commit it will no longer be visible in the project history.

Did you forget to include something in your last commit message?

Did you make a typo?

Did you add something into your commit message that is not relevant?

Don’t worry!

Git has a solution for you: the git commit –amend command.

The syntax for the amend command is as follows:

git commit --amend

You can use this command without the -m flag. If you do, an interactive text editor will be opened up in which you can replace the message from your older commit. Save and exit the text editor and your change will be made.

If you’d like to use the -m flag here’s an example of what that would look like.

git commit --amend -m “this fixes the previous oopsies”

Say that your last commit is missing a crucial file. Without it, you will be fired immediately. We can use the git commit –amend command to get out of this bind and fix the issue.

To change the files in a commit, first add the files you want to be included in your commit:

git add redemption.exs

If you want to remove a file from a commit, you can use git rm:

git rm garbage.exs

Once you have made the changes to a repository, you are ready to amend your commit. You can do this by using the –no-edit flag:

git commit --amend --no-edit

This command will change the files in your last commit. It will not change the message associated with the commit because we have not used the -m flag.

Next all that’s left is pushing your new changes up.

In conclusion: git --amend is very very useful! It can help you keep your commit history clean, so that when one of your colleagues (or future you) is referring to the commit history, it’s not cluttered up with simple fixes for things like typos and linter cleanup. A good rule of thumb is if your fix isn’t changing the code behavior (looking at you, whitespace cleanup), git --amend is a good option. If you’re not sure, ask your senior devs what they prefer.

Photo Credit: Ken Suarez

You've successfully subscribed to SmartLogic Blog
Great! Next, complete checkout for full access to SmartLogic Blog
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.