AI Hints
Home›Git & GitHub Tutorial›Fixing Real Mistakes
Git & GitHub · Lesson 100 of 144

Rescuing Detached Commits

Save them on a branch.

⏱ 2 min read▶ Video at 1:49:52🎓 Free
Watch this lesson in the Git & GitHub courseWatch on YouTube ↗Full Git & GitHub course

You visited an old commit, got inspired, and made a commit there, on a detached head. If you switch away now, that commit has no branch holding it, and it could get lost. The fix is one command.

Rescuing Detached Commits
From the video: Rescuing Detached Commits
  • Committed on a detached HEAD
  • No branch is holding it
  • One command saves it

Save it with a branch

Status confirms we're detached, and the log shows our new commit, try an idea. Git switch, dash c, idea, creates a branch right here, holding the commit. Now we're safely on a branch, and we can switch to main whenever we like.

git
git status
HEAD detached from 0ba6049
nothing to commit, working tree clean
git log --oneline -n 1
69d4ec6 (HEAD) Try an idea
git switch -c idea
Switched to a new branch 'idea'
git branch
* idea
  main

If you already switched away

Already switched away, and the commit seems lost? The reflog remembers it. Find its hash in git reflog, then create a branch at that hash, with git branch, a name, and the hash. Git also prints a warning with the hash when you leave a detached head, so look out for it.

Lost it?git reflog
Findthe commit's hash
Rescuegit branch idea <hash>
WatchGit's warning message

Summary

On a detached head, git switch dash c saves your commits on a new branch. If it's too late, the reflog still has them. Next, decoding common Git error messages.

Key takeaways
  • git switch -c <name>
  • Or: git branch <name> <hash>
  • The reflog remembers
Next up: Common Error Messages — what they really mean