What's the Difference Between Head^ and Head~ in Git?
Better Stack Team
Updated on August 12, 2024
In Git, HEAD^
and HEAD~
are used to refer to previous commits, but they have slightly different meanings and uses. Here’s a detailed explanation of each:
HEAD^
(Caret Notation)
- Syntax:
HEAD^
orHEAD^n
wheren
is an optional number. - Meaning: Refers to the parent commit(s) of the
HEAD
commit. - Usage:
HEAD^
is shorthand forHEAD^1
, which refers to the first parent of the current commit. In the case of a merge commit, it refers to the first parent (i.e., the commit that was on the branch before the merge).HEAD^2
refers to the second parent of a merge commit. Merge commits have more than one parent, so you can specify which parent you want to refer to.
Example:
git log HEAD^
This will show the log of the commit immediately before the current commit.
HEAD~
(Tilde Notation)
- Syntax:
HEAD~n
wheren
is a number. - Meaning: Refers to the commit that is
n
commits beforeHEAD
in the commit history. - Usage:
HEAD~1
refers to the commit directly before the current commit, which is equivalent toHEAD^
orHEAD^1
.HEAD~2
refers to the commit that is two commits before the current commit, and so on.
Example:
git log HEAD~2
This will show the log of the commit that is two steps before the current commit.
Key Differences
- Number of Parents:
HEAD^
specifically targets the parent(s) of the current commit. For a regular commit, it’s the immediate predecessor. For a merge commit, it allows specifying which parent to reference (first or second).HEAD~
is used to navigate a specific number of commits back in the history, regardless of whether the commits are regular or merge commits.
- Usage Context:
- Use
HEAD^
when you need to reference the immediate parent or a specific parent of a merge commit. - Use
HEAD~
when you want to refer to a commit that isn
steps back in the commit history from the current commit.
- Use
Examples
Referring to Parent Commits:
git show HEAD^ git show HEAD^2
These commands show the first parent and the second parent (if it exists) of the current commit.
Navigating Back in History:
git show HEAD~1 git show HEAD~3
These commands show the commit one step back and three steps back from the current commit.
Summary
HEAD^
:- Refers to the parent commit(s).
HEAD^
orHEAD^1
is the first parent.HEAD^2
is the second parent of a merge commit.
HEAD~
:- Refers to a commit
n
steps back in history. HEAD~1
is one commit back,HEAD~2
is two commits back, etc.
- Refers to a commit
Understanding these notations helps navigate and manipulate commit history effectively in Git.