Home > Enterprise >  Revert a git commit with git reset. I used "main" instead of "HEAD". Is it an is
Revert a git commit with git reset. I used "main" instead of "HEAD". Is it an is

Time:08-27

I used these commands to roll back one of my git commits:

$ git switch main
$ git reset --hard main~1
$ git push origin main --force-with-lease

Even though everything worked fine, I noticed that many people use HEAD~1 instead of main~1. Did I do something wrong by using main~1 instead of HEAD~1? main is the only branch I had in the repository when I did the reset.

CodePudding user response:

Your solution works fine if you are on the main branch currently.

HEAD references the currently checked-out commit. If you have checked out the main branch then HEAD and main both reference the same thing.

To test this you can use git rev-parse HEAD or git rev-parse main which will result in the same hash code if you have checked out the main branch.

The git reset --hard HEAD~1 works on all branches to undo the latest commit of this branch.

If you use git reset --hard main~1 on branch develop you will hard reset your develop branch to the second latest commit on branch main which is probably NOT what you wanted.

I tested it out with some sample hash codes for you. Feel free to check out different branches in your project and check which commit is referenced by HEAD.

git checkout main
git rev-parse main
# Some hash like 54668ebf7678bef9f6274a8c3bc91e1bdef3cde5
git rev-parse HEAD
# Same hash code still like 54668ebf7678bef9f6274a8c3bc91e1bdef3cde5
git rev-parse develop
# Other hash code like aa9f1cccadf548913c582793ec3cda4dd4ec019a

Now, if you are on develop, HEAD will look at develop and not at main.

git checkout develop
git rev-parse main
# main hash 54668ebf7678bef9f6274a8c3bc91e1bdef3cde5
git rev-parse HEAD
# develop hash aa9f1cccadf548913c582793ec3cda4dd4ec019a
git rev-parse develop
# develop hash aa9f1cccadf548913c582793ec3cda4dd4ec019a
  • Related