Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Undo Git Commit Amend So You Can Make a Separate Commit

undo-git-commit-amend-so-you-can-make-a-separate-commit.jpg

This can be helpful to break apart 2 commits so you can go back and make a separate commit with your latest changes.

Quick Jump:

If I’ve been doing a few git commit --amend --no-edit commands sometimes my brain goes into auto-complete mode and will add --amend --no-edit out of habit on my next commit.

Of course this is a problem when you want to create a separate commit, otherwise if you amend a commit then the changes will be rolled into your most recent commit instead of making a new one. Oops!

Thankfully it’s super easy to undo things in a way where whatever you amended will be separated out of your latest commit and be staged for commit:

# If you get an error in your shell, try wrapping HEAD@{1} in quotes.
git reset --soft HEAD@{1}

As always if you’re rewriting history, this is a thing to do before you push your code!

There’s a difference between HEAD~1 and HEAD@{1} and neither are specific to --amend.

If we used ~1 it would have completely undid the previous commit so now you would be left having to re-do that commit and also the new commit you want afterwards. Instead, @{1} will keep that previous commit and automatically stage your amended changes so you can commit it separately. The docs go into more detail about HEAD@{1}.

There are other use cases for HEAD@{1} but it’s my new goto trick for undoing an amend.

I had this happen to me recently when I was making changes to my Dockerized Rails starter app and I amended adding Hotwire Spark into the same commit where I replaced Sprockets with Propshaft. These are separate things, so the above command helped resolve that.

The video below demos how this works in a git repo.

# Demo Video

Timestamps

  • 0:23 – Showing the problem
  • 1:07 – Solving this in an inefficient way
  • 2:28 – Solving it in a better way
  • 3:23 – Taking a look at reflog and the differences between the 2

When was the last time you had to do this? Let me know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments