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
Published 4 years ago
Updated 3 years ago

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.

egghead
egghead
~ 5 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today