Sub topic 3
HEAD: where you are now
This chapter assumes you can run git init, git add, git commit, git status, and git log. It also assumes Git 2.23 or later, which provides git switch. A branch is a pointer to a commit. HEAD tells Git which branch you are currently on.
What HEAD is
HEAD is a special reference that marks the commit you have checked out. Usually it does not point at a commit directly. It points at a branch name, and that branch points at a commit. Git follows the chain to find your current commit.
When you commit, Git creates the new commit with the current commit as its parent. It then moves the branch that HEAD names to the new commit. HEAD itself does not change. It still names the same branch.
Looking at HEAD
Git stores HEAD in a small text file inside the repository. You can read it directly or ask Git to resolve it.
cat .git/HEAD
git symbolic-ref HEAD
git rev-parse HEAD
git branch --show-currentOn a branch, the first command prints ref: refs/heads/main. The second prints refs/heads/main. The third prints the full SHA (the commit's 40-character ID) that HEAD resolves to. The fourth prints only the branch name.
Moving HEAD
Switching branches changes what HEAD names. It also updates your working directory to match the target commit.
git switch feature/login
git branch --show-current
git switch -The last command, git switch -, returns to the branch you were on before.
HEAD also works as a starting point for relative references:
HEAD~1is the first parent of the current commit.HEAD~3is three commits back along first parents.HEAD^2is the second parent of a merge commit.
git show HEAD~1
git diff HEAD~2 HEADCommon errors
- Confusing HEAD with the branch.
git reset --hard HEAD~1moves the current branch back one commit. It does not move HEAD to a different branch. - Switching with uncommitted changes. Git refuses the switch if your changes would be overwritten. Commit them, or run
git stash, and then switch. - Checking out a commit instead of a branch.
git switch <sha>is refused unless you add--detach. If you usegit checkout <sha>, HEAD points directly at a commit and the branch link is gone. This is a detached HEAD, covered in a later chapter.
Summary
HEAD answers the question "where am I?". It normally names a branch, and each commit you make moves that branch forward. Switching branches moves HEAD to a different name.
Exercise
You are on branch main, which points at commit C. You run git commit, creating commit D. Which pointers move, and what does .git/HEAD contain afterward?
Show answer
The branch main moves from C to D. HEAD does not move, because it still names main. .git/HEAD still contains ref: refs/heads/main.
Exercise
Which command prints the full SHA of the commit you are currently on?
Show answer
git rev-parse HEAD