18 Apr, 2025
3 min read
How well do you understand git and git commands? It is something I struggled with a lot earlier in my career. You think you're a git pro until you mix up git rebase with git merge, and you're about to lose 5 hours of work.
If you've ever worked with git then you have definitely come across the term HEAD. It's not an acronym. It actually refers to the latest commit in your repository based on where you are at the moment. Walk with me.
There are essentially two HEAD states in git. The first is Normal/Attached HEAD state, and the other is Detached HEAD state. Say you check out to a branch, develop. Your HEAD points to develop which then points to the latest commit on develop. It is in normal HEAD state. But if instead you check out to a commit with hash "abcdefg". Your HEAD points directly to the commit, and because it is no longer attached to a branch, it enters Detached HEAD state.
As you move through your repository, HEAD changes along with you, keeping track of your commit histories. If you are in develop branch and you make a new commit - "feat: new auth". Your HEAD updates and points to that new commit. It does this as more commits are made.
When you check out to a new branch from an existing branch, HEAD in your new branch points to the same commit as the older branch, because both branches are in the same state. Following our scenario, this would mean that from develop, you check out to a new branch feat/pricing. Your HEAD is in Attached state and points to your branch feat/pricing which points to the latest commit "feat: new auth", even though that commit was done in develop.
I'm sure by now you are wondering why you need all of this information. Have you ever been in a situation where you're working on a branch, casually fixing a bug, and you make a quick commit: git commit -m "fix: handle login edge case". Then you look up... and realize 😱 You were supposed to be in the develop branch and not feat/pricing. Now you've got a commit on the wrong branch 💔
Solution: Since the commit is still local and you haven't pushed it, you can safely rewind: git reset HEAD~1 This tells git to take you (your HEAD) back to the commit before your most recent commit. So git takes you one step back to "feat: new auth" commit, and keeps your changes in the staging area.
You can now safely check out to the correct branch - develop - and recommit the changes kept for you.
Understanding HEAD tells you: - Where you are (HEAD) - Where you were (HEAD~1) - How to move carefully between commits without losing your work (or your team's trust 😅)
I'm happy to answer any questions you might have, so ask away! I'll be referencing this article in the future with more git related topics. Should be fun😇
Feel free to reach out to me if you're looking for a developer, have a query, or simply want to connect.