Video in progress
What does the message "You are in 'detached HEAD' state" mean, and will the commits you make in this state be lost?
HEAD points directly at a commit, not at a branch. You can commit in this state, but no branch points to those commits, so if you switch to another branch they are left "dangling". To keep them, run git switch -c new-branch.
📖 Answer
This state usually appears like this: you move to a tag (git checkout v2.1.0), to a commit hash, or you stopped in the middle of a rebase.
For looking at code and running tests it is completely normal. The problem starts when you commit here and then git switch main: the commits are not attached to anything and do not show in git log.
git switch --detach v2.1.0
# ... fix, commit ...
git switch -c hotfix/2.1.1 # the commits are now on a branch, safe
If you have already moved to another branch, do not panic:
git reflog # find the hash of that commit
git branch rescue 9d3f2ab
Git does not delete such commits right away: the HEAD reflog points to them, such entries are kept for 30 days by default, and only after that can git gc clean them up.
Sign up to mark studied questions and save your progress.