Test with Older Commits
In the previous steps, we learned about HEAD
and how to get its commit hash. Now, let's see how Git refers to older commits.
Currently, we only have one commit in our repository. To demonstrate how to refer to older commits, we need to make another commit.
First, let's add another line to our message.txt
file. Use the echo
command with >>
to append text to the file:
echo "This is a second message." >> message.txt
Now, let's check the status:
git status
You should see that message.txt
has been modified:
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: message.txt
no changes added to commit (use "git add and/or git commit -a)
Now, stage the changes and create a new commit:
git add message.txt
git commit -m "Add a second message"
You should see output indicating a new commit was created:
[master a1b2c3d] Add a second message
1 file changed, 1 insertion(+)
Now we have two commits. Let's view the log again:
git log --oneline
The --oneline
option gives a concise view of the log. You should see something like this (the hashes will be different):
a1b2c3d (HEAD -> master) Add a second message
e4f5g6h Send a message to the future
The top commit is the newest one, and it's where HEAD
is pointing. The commit below it is the older one.
Git provides ways to refer to commits relative to HEAD
. The commit directly before HEAD
can be referred to as HEAD~1
or HEAD^
. Let's try getting the hash of the previous commit using git rev-parse
:
git rev-parse HEAD~1
You should see the hash of the first commit you made:
e4f5g6h7i8j9k0l1m2n3o4p5q6r7s8t9u0v1w2x3
This hash should match the hash of the "Send a message to the future" commit in your git log --oneline
output.
You can use HEAD~2
, HEAD~3
, and so on, to refer to commits further back in history. This relative referencing is very useful for navigating your project's history and performing operations on specific past versions.