Git Relative Refs
Links: 106 Git Index
Relative Refs¶
- Specifying commits by their hash isn't the most convenient thing ever when we want to move around, which is why Git has relative refs.
- With relative refs, you can start somewhere memorable (like the branch
bugFix
orhead
) and work from there. - Mostly used relative refs:
- Moving upwards one commit at a time with
^
- Moving upwards a number of times with
~<num>
- Say you want to move a lot of levels up in the commit tree. It might be tedious to type
^
several times, so Git also has the tilde~
operator.
- Say you want to move a lot of levels up in the commit tree. It might be tedious to type
- Moving upwards one commit at a time with
Examples¶
Example: Using ^
¶
- Initial state:
git checkout main^
- Notice the
head
moved and not themain
branch - Move 1 step relative to
main
- We can also move relative to
head
. Initial state git checkout C3; git checkout HEAD^; git checkout HEAD^; git checkout HEAD^
Example: Using ~
¶
- Initial state:
git checkout HEAD~4
: excludes the current commit
Example: Moving Branches¶
- This is a use case of relative refs.
- Initial state:
git branch -f main HEAD~3
:-f
means forceful
Last updated: 2022-06-10