Firstly, it’s essential to understand what HEAD is. In Git, HEAD is a special pointer or reference that points to the latest commit in the branch we’re currently on. Whenever we make a new commit, HEAD moves forward to point to that commit.
The ~ notation provides a way to move multiple steps backward in the commit lineage, specifically through the first parent. Let’s consider the following diagram showing a commit history:
If HEAD points to commit A in the following structure, then:
HEAD~ or HEAD~1: These are equivalent, and both point to the current commit’s first parent, B.
HEAD~2: This takes us two steps back, but always moving through the first parent. HEAD~2 would point to commit C.
In simple terms, ~ specifies the ancestors of a particular commit. This means that HEAD~3 is the same as HEAD~~~.
If we have ~, why do we need an alternate notation? What if a commit has multiple parents? ~ allows us to navigate ancestors, but it cannot be used to specify parents. The ^ notation allows us to specify and navigate to parent commits.
Let’s consider the following commit history:
How will we navigate to E or F?
If HEAD points to commit A in the following structure, then:
HEAD^ or HEAD^1: Points to the first parent of the current commit. In non-merge commits like A that have only one parent, HEAD~, HEAD^, and HEAD^1 will point to the same commit, B.
In the case of merge commits (commits that result from merging two branches), like in the case of C, there are multiple parents (D and E). This is where the ^ notation becomes especially useful.
C^1: Refers to the first parent, D. This will be determined by whether the parent is on the same branch or if it was merged in.
C^2: Refers to the second parent, E. This is a branch that is merged, so it will be assigned as the second parent.
It is important to understand that HEAD^^ does not always mean the same as HEAD^2. Let’s consider the following case to understand why:
So we can see that from HEAD (at A), using ^^ will take us to C, whereas using ^2 will take us to D.
Free Resources