Time Travel in Git with Detached HEAD
Imagine your supervisor tells you:
"This feature was working yesterday but is broken today — you must have caused it!"
How do you prove whether it was really your change or the bug was already there?
This is where Git time travel comes in handy. You can move to a specific commit from the past, see exactly what the code looked like, and even compare it with your current version. Let’s see how.
Scenario Setup
Create a new project:
mkdir project8
cd project8
git init
Make a file and commit it:
echo "line added in first commit" > feature.txt
git add feature.txt
git commit -m "First commit"
Add two more commits:
echo "line added in second commit" >> feature.txt
git commit -am "Second commit"
echo "line added in third commit" >> feature.txt
git commit -am "Third commit"
Check history:
git log --oneline
Output:
c3e4f3c Third commit
9a7b1d2 Second commit
4b1c2a1 First commit
Switching to an Old Commit
Normally, git switch <branch> works for branches. But here we want to move to a specific commit.
git switch --detach 9a7b1d2
Now Git prints:
HEAD is now at 9a7b1d2 Second commit
Open the file:
cat feature.txt
# line added in first commit
# line added in second commit
You’ve successfully traveled back in time 🚀.
Visual Representation
Using Git Checkout (Old Way)
The same can also be done with git checkout:
git checkout 4b1c2a1
Output:
Note: switching to '4b1c2a1'.
You are in 'detached HEAD' state...
It’s the same as git switch --detach.
Warning About Detached HEAD
When you are in a detached HEAD state:
- You are not on a branch.
- If you make new commits here, they are not referenced by any branch.
- Git’s garbage collector may eventually remove them.
For example:
echo "temp change" > temp.txt
git add temp.txt
git commit -m "Temporary commit"
If you now switch back to main:
git switch main
That temporary commit is left dangling. It may be garbage-collected later.
🔑 Rule of Thumb: Avoid committing in detached HEAD unless you plan to create a new branch from there.
Practical Use Case
- Reproduce an old version of the project exactly as it was.
- Prove whether a bug existed in earlier commits.
- Compare file changes between two points in time.
Summary
- Use
git switch --detach <commit-id>orgit checkout <commit-id>to view old commits. - This is called detached HEAD state.
- Never commit in detached HEAD unless you create a new branch to save your work.
- Perfect for time travel in Git to debug or verify past code.
Keep Learning 🚀
👉 Subscribe to Learning Ocean – Subscribers get coupon codes for my courses, early access to blogs and courses, and even exclusive YouTube videos.
👉 My YouTube Channel – More videos, more fun, and lots of learning!
👉 📺 Watch this topic in video form
Stay curious, keep coding, and let’s make learning fun together! 🎉