Test with Detached and Normal HEAD
In the previous steps, we learned that HEAD
usually points to a branch, like master
. This is the "normal" state. However, HEAD
can also point directly to a specific commit. This is called a "detached HEAD" state.
Let's see what a detached HEAD
looks like. First, we need the commit ID of our first commit. We can get this using git log --oneline
:
cd ~/project/my-time-machine
git log --oneline
You should see output similar to this (your commit ID will be different):
a1b2c3d (HEAD -> master) Send a message to the future
The first seven characters (a1b2c3d
in this example) are the short commit ID. Copy this ID.
Now, let's move HEAD
to point directly to this commit using git checkout
:
git checkout <your_commit_id>
Replace <your_commit_id>
with the actual short commit ID you copied from git log --oneline
. For example:
git checkout a1b2c3d
You will see output indicating that you are in a detached HEAD state:
Note: switching to 'a1b2c3d'.
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 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, if you want to make this branch stay, use:
git branch <new-branch-name> <your_commit_id>
Switched to commit a1b2c3d
Now, let's check the status again:
git status
The output will clearly show that you are in a detached HEAD state:
HEAD is now at a1b2c3d Send a message to the future
nothing to commit, working tree clean
And if we use git symbolic-ref HEAD
, it will show an error because HEAD
is not a symbolic reference to a branch:
git symbolic-ref HEAD
This command will likely produce an error or no output, indicating that HEAD
is not a symbolic reference.
To return to the normal state where HEAD
points to the master
branch, we can checkout the master
branch:
git checkout master
You should see output like this:
Switched to branch 'master'
Now, git status
will show you are back on the master
branch:
git status
Output:
On branch master
nothing to commit, working tree clean
And git symbolic-ref HEAD
will again show the symbolic reference:
git symbolic-ref HEAD
Output:
refs/heads/master
Understanding the difference between an attached HEAD
(pointing to a branch) and a detached HEAD
(pointing directly to a commit) is important for navigating your project's history and performing advanced Git operations.