How to undo the last git commit?

There are situations where you just committed a change in git and just after that realized you made a mistake in the last commit. If you haven’t pushed that code then the last local changes can be undone with the following command.

git reset --soft HEAD~1

What this does is that it uncommits the last change and puts that back in a staged state. That means if you run the git status command then you will see those changes in your working directory. Now you can make further changes to that revision and then commit again.

Creating Git branch in detached HEAD State

Recently, I came across a situation where I checked out a git branch and it showed me this message:

You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout.

I guess this happened because the branch that I was checking out was rebased. Otherwise, it usually happens when you checkout a commit with its hash. But in my case, I was checking out a branch. Anyway, this is a special state called “detached HEAD”. While you can commit changes in this state, those commits don’t belong to any branch and will become inaccessible as soon as you check out another branch. But what if you do want to keep those commits?

The answer, unsurprisingly, is to use the “checkout” command again and you can use the same branch again:

git checkout <branch> #now you're in detached head state
# do some work and stage it
git add --all
git commit -m "add some work while in detached head state"
git branch <branch>
git checkout <branch>

Pretty easy, right?