What is HEAD and HEAD~n in Git?
When working with Git, you will often read about "HEAD", "HEAD~1", "HEAD~2", etc. But what exactly does this mean and what do you need it for? ¯\_(ツ)_/¯
Let’s say you have the following commits and corresponding hashes ordered descending by their creation timestamp:
|Date of creation
What does HEAD mean?
HEAD points to the latest commit of the branch you are currently working on. In our example, HEAD points to the third commit (i.e. the commit with the hash
What does HEAD~n mean?
If you see something like HEAD~n (e.g. HEAD~1 or HEAD~2), then this means n commits before HEAD. In our example HEAD~1 points to the second commit (i.e. the commit with the hash
def) and HEAD~2 points to the first commit (i.e. the commit with the hash
What do I need this for?
You have to work with HEAD or HEAD~n in case that you want to
- reverting your local uncommitted changes
- checking out a specific commit.
In case that you want to revert your local uncommitted changes, you need the following git reset command:
git reset --hard HEAD
In case that you want to undo commits, you can find more information in this post.
For full reference see Git references documentation.