빠른 비교
| 상태 | HEAD가 가리키는 것 | 새 commit 위치 |
|---|---|---|
| 일반 branch | branch ref | branch가 앞으로 이동 |
| detached HEAD | commit hash | 이름 없는 commit 체인 |
| tag checkout | tag가 가리키는 commit | detached HEAD |
| 임시 실험 | 특정 commit | branch를 만들면 보존 |
구조 이해
HEAD는 현재 작업 기준을 가리키는 포인터다
일반적인 상태에서 HEAD는 직접 commit을 가리키기보다 현재 branch를 가리킨다. 예를 들어 main에서 작업 중이면 HEAD는 refs/heads/main을 가리키고, main branch는 실제 commit hash를 가리킨다. 새 commit을 만들면 branch ref가 새 commit으로 이동하고 HEAD는 계속 그 branch를 따라간다.
git symbolic-ref --short HEAD
git rev-parse HEADdetached HEAD는 branch가 아니라 commit을 직접 체크아웃한 상태다
특정 commit hash나 tag를 checkout하면 HEAD가 branch 이름이 아니라 commit 자체를 가리킬 수 있다. 이 상태가 detached HEAD다. 과거 상태를 확인하거나 특정 commit에서 테스트를 실행할 때는 유용하지만, 여기서 새 commit을 만들면 branch 이름이 붙지 않은 commit 체인이 생긴다.
git switch --detach <commit>
git switch -c experiment-from-old-commitdetached 상태에서 만든 commit은 branch를 붙여야 안전하다
detached HEAD에서 만든 commit도 즉시 사라지는 것은 아니다. 하지만 branch나 tag 같은 ref가 없으면 나중에 찾기 어려워지고, reflog 만료 후에는 복구가 어려워질 수 있다. 실험이 의미가 있다면 바로 git switch -c <name>으로 branch를 만들어 commit을 보존한다.
tag는 release 기준점이지 작업 branch가 아니다
tag를 checkout하면 보통 detached HEAD가 된다. tag는 특정 release commit을 가리키는 기준점으로 쓰고, 수정 작업은 tag에서 새 branch를 만들어 진행하는 편이 안전하다. release hotfix가 필요하다면 tag checkout 후 바로 hotfix branch를 만들고 그 branch에서 commit한다.
체크포인트
| 상황 | 확인/대응 |
|---|---|
| 현재 branch 확인 | git branch --show-current |
| detached 여부 확인 | git status |
| 현재 commit 확인 | git rev-parse --short HEAD |
| detached commit 보존 | git switch -c <branch> |
| 실수로 빠져나감 | git reflog로 commit 찾기 |
공식 참고: Git Glossary, Pro Git: Git References
주의할 점
detached HEAD에서 commit한 뒤 다른 branch로 이동하면 작업이 사라진 것처럼 보일 수 있습니다. 의미 있는 commit을 만들었다면 바로 branch 이름을 붙이고, 이미 이동했다면 reflog에서 commit hash를 찾아 branch를 만들어 보존하세요.
git reflog
git switch -c recovered <commit>참고 링크
2 sources