Referencing git commits by names, IDs, etc.
A given git commit can be referenced by many different “names.” Here are some examples:
How | Example | Notes |
---|---|---|
Commit id | 77bt34fc6 | You can use as little or as much of the id as you want. Although if it matches more than one commit, Git will complain. The first 8 characters is usually enough. |
Branch name | my-branch | A special pointer to a particular commit. Hint: it’s the latest commit in the branch. |
Tag name | my-tag | A pointer to a particular commit, not necessarily a branch tip. It’s like an alias to a particular commit id. |
The current latest commit | HEAD | Always points to the top commit in the current branch. |
Any name with ^ | HEAD^ , 77bt34fc6^^ , etc. | Putting ^ at the end always refers to “the previous commit.” You can also supply a commit reference that already has ^ . E.g. 77bt34fc6^^ would be “the commit before the commit before 77bt34fc6 .” You can extend these as far as you want, but it’s usually better to use the ~N construct instead (see below). |
Any name with ~N where N is any positive integer | HEAD~2 , 77bt34fc6~4 , etc. | “The commit ’n’ commits before the one specified.” Note the commits are zero-indexed, i.e. HEAD~0 is equivalent to HEAD |
Examples
Given the following commits and current HEAD:
$ git checkout my-branch
$ git log --oneline
ac9949d (HEAD -> main) Tenth commit
9a06237 Ninth commit
3cdb729 Eighth commit
0d12987 Seventh commit
6498f71 Sixth commit
2a4407b Fifth commit
f8d16dd Fourth commit
2eddf4c Third commit
421eb72 Second commit
bb9af76 First commit
Here are some example references the above commits:
Reference | Refers to commit |
---|---|
my-branch | ac9949d |
HEAD | ac9949d |
HEAD~4 | 6498f71 |
6498f715ff1a5d7f7db096 | 6498f71 |
3cdb729~2 | 6498f71 |
0d12987^ | 6498f71 |
3cdb729^^ | 6498f71 |