Git Amend: How To Edit Your Last Commit

Git’s amend command is so simple, yet so powerful. I personally use it multiple times a day and even have a bash alias for it. Why is amending so useful? The answer is simple: programmers make lots of mistakes. Mistakes are a part of the job. Git amend fixes mistakes as simple as a commit message typo. On the other hand, git amend can be significant enough to improve your (team’s) entire commit history.

Below, I’ll explain why git amend is so useful, and how you can start using it immediately. Let’s get started!

Why Use Git Amend?

There are a couple of key practical uses here. For the most part, git amend aims to fix a mistake. In other words, it “amends” you. It’s pretty useful in several cases.

Use Case 1: Changing Commit Message Typos
Have you ever saved a commit and immediately think of a better or more descriptive commit message? Happens all the time. To amend, you don’t even need to make any code changes. With git amend, you can change only the commit message.

Use Case 2: Appending Code To The Last Commit
Maybe you made a follow up change that doesn’t exactly deserve its own commit. Often times, a single commit isn’t final. You don’t have to “commit” to it. You can take a small typo or an entire new file and add it to the previous commit. This helps keep git logs focused.

You can add as many changes to the same commit as necessary, as long as you don’t make an entire new commit. So how exactly do we do this? It’s very easy!

How To Use Git Amend

Using git amend is pretty straightforward. First, you need to add your staged changes. This should be a simple git add . Once your changes are ready, run git commit --amend. That’s pretty much it!

Nano can look confusing at first, so just follow the steps below to get through it.

Once you run the latter command, you will be prompted by nano(gits default text editor) to proceed with your changes. You can get through nano by going through these steps:

  • Typing in your new git description. Don’t change anything if you want to keep it the same.
  • Hit CTRL+X to continue. If you didn’t change the commit message, it should exit immediately. If not, you can hit CTRL+Y to save, or CTRL+N to cancel.
  • There are other options, just look at the bottom of your terminal window. Though, the above is all you should need for basic uses.

Saving Some Time With a Bash Alias

For a basic amend, you need to type in git add . && git commit --amend. If you think you’ll do this often, it’s nice to have an alias that can save a few keystrokes.

Here’s what I use: alias gitamend="git add . && git commit --amend"

Use whatever works for you. The shortest name I can think of is gita, which is only 4 keystrokes. Pretty handy!

That’s all you should need to get started. It’s a pretty simple command and there isn’t much more to it, but feel free to peek through the additional resources below. Enjoy!