What is Detached Head in GIT

HEAD is a symbolic ref pointing the branch which is also a ref pointing the latest commit oid. like this

1
2
$ cat .git/HEAD 
ref: refs/heads/main

In this case, if u make a new commit, git will not actually change the HEAD but change the branch pointed by HEAD. Bad thing happens if u checkout a commit by its oid. Checking a commit by its oid means HEAD will be not be a symbolic ref and HEAD will point at a commit directly. like this

1
2
3
$ git checkout e53fae9913340f71ade680e5b1c477892a2abd90
$ cat .git/HEAD
e53fae9913340f71ade680e5b1c477892a2abd90

e53fae9913340f71ade680e5b1c477892a2abd90 is a commit id.

U will get a warning when u try git checkout <commit oid>

1
2
3
4
5
Note: switching to 'e53fae9913340f71ade680e5b1c477892a2abd90'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

Now if u do some changes and commits, HEAD will record everything. But if u switch to a branch, u will lose the changes and commits because there is no branch tracking ur modification (these commits are recorded by git but u can only track them via their oid). U should avoid this situation (create a new branch instead), or tag the commits before leaving.