Explore Old Commits with a Detached HEAD, and then Recover

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet

To poke around in old code, we can checkout the hash of an old commit with git checkout [HASH] - but then we'll be in a "detached HEAD" state.

Detached HEAD just means that HEAD is not pointing to a branch. That's problematic if we want to save the work that we do in that state - so we first have to make a new branch where we are with git checkout -b my-new-branch

Then, any changes we make can be committed to that new branched and saved.

Instructor: [00:00] Let's look at our local git log with git log one line. Let's go all the way back to where we added the index.html and app.js files.

[00:10] If we want to explore what the code looked like at that time, we can gitCheckout this hash. Now, it says we're in a detached head state. If we go look at our app.js code, this is when we first edited, just had the comment at the top.

[00:25] What a detached head means if we do a git log one line, we can see that our head is not pointing to a branch right now. Instead, it's pointing to a commit. This is problematic because if we make changes right now, and then move our head away, then those changes could be lost.

[00:42] We could just poke around and then switch to a branch, and that would be fine. If we want to make changes here, then what we have to do is do what it says right here, which is to check out a new branch at this hash. We're going to gitCheckout a new branch, and we'll just call this exploring a JS feature.

[00:59] If we do get status, we're no longer in a detached head state. If we do git log online, we can see that our head is now successfully pointing to a branch. Now, any changes we make here won't get lost. If you do get branch -vv now, you can see our new branch here, which is not a remote branch, and it's different than the other two branches, which are remote branches.