Test Non-Existent Files
In the previous steps, we successfully used git ls-tree
and git log -- <file>
to inspect a file that exists in our Git repository. Now, let's see what happens when we try to use these commands on a file that does not exist in the repository's history.
Make sure you are in your project directory:
cd ~/project/my-time-machine
First, let's try to use git ls-tree
on a non-existent file, for example, nonexistent.txt
:
git ls-tree HEAD nonexistent.txt
You should see no output. This is because git ls-tree
only lists entries that are present in the specified tree (in this case, the tree at HEAD
). Since nonexistent.txt
is not in the latest commit's tree, it doesn't show anything.
Now, let's try to use git log
on the same non-existent file:
git log -- nonexistent.txt
You should see output similar to this:
fatal: no such path 'nonexistent.txt' in HEAD
This is a different behavior! git log -- <file>
specifically looks for commits that affected the given file path throughout the history. If the file path has never existed in any commit, Git tells you that there is "no such path".
This difference in behavior highlights how these commands work:
git ls-tree
inspects a specific snapshot (commit) and lists its contents.
git log -- <file>
searches the entire history for changes related to a specific file path.
Understanding these differences helps you choose the right command for the task. If you want to see what files were in a commit, use git ls-tree
. If you want to see the history of a file, use git log -- <file>
.