본문 바로가기

IT/Git

[Git] Detached Head

git checkout origin/feat*

를 했더니 detached head라는 말이 떴다.

sjkim@cv2080ti2way:~/workspace/eo-detector-lib$ git checkout origin/feat-fix-slice-bug
Note: switching to 'origin/feat-fix-slice-bug'.

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.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 4bb0bf2 #71 Fixed the bug by applying all the values ​​for n_of_full_frame

HEAD가 branch를 가리키는 게 아니라 commit을 가리키고 있을 때 나는 오류이다.

 

 

Detached Head

깃으로 버전관리 하다보면 작업내용을 commit하고 원격저장소에 push할 때, detached head 상태에 있다며, push가 reject될 때가 있다. 빨리 저장소에 push해야하는 상황에서 이런 오류를 마주치면 당황하

devcamus.tistory.com

Detached Head란, 말 그대로 head가 (branch로부터) 떨어져있는 상태를 뜻한다. 

즉, branch를 통해서가 아니라 직접 다이렉트로 commit을 참조하고 있는 상태를 뜻한다. 

 

 

1.현재, head는 master를 통해서 69084f3라는 revision number를 가진 commit을 참조하고 있다.

이 커밋은 22d1c79라는 커밋 이후에 두 번째로 한 커밋이다.    

 

 

2. 그런데, 어떤 이유로 나도 모르게(주로, 위에서 언급한 gui환경에서의 부주의 때문에) 첫번째 커밋으로 체크아웃해서 detached head 상태가 되었다.     

 

 

3. 여기서 head -> branch -> commit의 참조순서를 제대로 모르는 상태에서, 다시 이전으로 원상복구 한답시고 두 번째 커밋인 69084f3으로 check out했다.    

 

 

4.

상황1. 뭐가 잘못된 것 같은데, 무슨 문제인지 몰라서 소스코드에 띄어쓰기 한칸 더 넣고 새로 커밋을 한다.  하지만 ide 내장 git graph에서는 내가 방금 한 새 커밋은 온데간데 보이지도 않는다. 실제 상황은 아래 그림과 같이, detached head는 세 번째 커밋인 783fbf2를 참조하고, master 브랜치는 여전히 두 번째 커밋을 참조하고 있다.

 

상황2. 3번에서 문제가 해결된 줄 알고 열심히 작업해서 세 번째 커밋을 하고 push하려니 reject 당했다. 뭐가 문제인지 파악하려고 git graph를 보니 내가 방금 한 커밋이 보이지 않는다. 

 

 

5. 4에서 상황 1의 경우, 세 번째 커밋은 별 필요가 없으므로 아래의 명령어를 쳐서, head가 master branch를 참조하게끔 하면 문제가 해결된다.

git checkout master

 

 

 

 

6. 4에서 상황 2의 경우, 세 번째 커밋을 유지하려면 아래의 명령어로, master branch를 세번째 커밋을 참조하게끔 만들고,

git branch -f master HEAD

git branch -f master HEAD로 master branch 이동

이어서 head가 master branch를 참조하게끔 branch로 checkout해주면 된다.

 git checkout master

git checkout master

 

 

매우 친절한 답변 뒤에 뼈때리는 진심어린 충고의 멘트가 너무도 와닿는다.

Learning Git in an IDE is a recipe for disaster.