I was trying to discard local changes by deleting a file and running:
git checkout HEAD^ src/
Now I’m stuck in a git detached head state and don’t fully understand what that means. How do I undo this and get back to a normal branch?
I was trying to discard local changes by deleting a file and running:
git checkout HEAD^ src/
Now I’m stuck in a git detached head state and don’t fully understand what that means. How do I undo this and get back to a normal branch?
I remember when I first got stuck in a git detached head state after trying to undo some local changes it felt confusing! Basically, you’re on a commit, not on a branch, so Git warns you.
To fix it, I just checked out my branch again using git checkout main (or replace main with your branch name). That moves you back to the latest commit on that branch and gets rid of the detached state. Just make sure you don’t lose any work you want to keep before switching!
Yep, Git detached head can throw you off. I once tried to reset files and ended up detached too. The key is that you’re “detached” because HEAD points directly to a commit, not a branch ref.
To recover, I ran git switch - or git checkout main to jump back to the branch I was working on. If you want to save changes made during the detached head, you can create a new branch from that commit first with git checkout -b temp-fix before switching back.
I’ve fixed this several times. The git detached head means HEAD points to a commit, not a branch, so any commits made won’t be saved on a branch unless you create one.
To undo your detached state, simply check out the branch you were on before:
git checkout <branch-name>
If you’re unsure which branch, git branch lists all local branches. This restores normal state and your working directory to the latest commit on that branch.
Avoid using git checkout HEAD^
if you want to keep working on your branch directly.