Revisiting old commits
The pointer HEAD
, which normally points to the branch main
which itself points to latest commit, can be moved around. By moving HEAD
to any commit, you can revisit the state of your project at that particular version.
The command for this is git checkout
followed by the hash of the commit you want to revisit.
For instance, we could revisit the first commit in our example with:
git checkout 24duu7i # Replace the hash by the hash of your first commit
Note: switching to '24duu7i'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:
git switch -c <new-branch-name>
Or undo this operation with:
git switch -
Turn off this advice by setting config variable advice.detachedHead to false
HEAD is now at 24duu7i Initial commit
This is the same as the command git switch --detach 24duu7i
: git switch
is a command introduced a few years ago because git checkout
can be used for many things in Git and it was confusing many users. git switch
allows to switch from one branch to another or, with the --detach
flag, to switch to a commit as is the case here.
Once you have seen what you wanted to see, you can go back to your branch main
with:
git checkout main
Previous HEAD position was 24duu7i Initial commit
Switched to branch 'main'
This is the same as the command git switch main
.
Be careful not to forget to go back to your branch main
before making changes to your project. If you want to move the project to a new direction from some old commit, you need to create a new branch before doing so. When HEAD
points directly to a commit (and not to a branch), this is called “Detached HEAD” and it is not a position from which you want to modify the project.
It is totally fine to move HEAD
around and have it point directly to a commit (instead of a branch) as long as you are only looking at a version of your project and get back to a branch before doing some work: