본문 바로가기
C.W.K.
Stream
Lesson 02 of 05 · published

git switch, checkout, detached HEAD

~20 min · switch, checkout, head

Level 0추적 전 새싹
0 XP0/47 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

branch에는 switch, 파일에는 restore

오랫동안 git checkout은 서로 다른 두 일을 맡았어. branch를 바꾸는 일과 이력에서 파일을 복원하는 일이야. 이 과적재는 입문자 실수를 자주 불렀지. git checkout file.js를 파일을 연다는 뜻으로 오해해 commit하지 않은 편집을 통째로 날리는 식이야. Git 2.23(2019)은 역할을 git switch(branch)와 git restore(파일)로 나눴어. 새 명령이 의도를 더 분명하고 안전하게 드러내니 현대적인 안내라면 이쪽을 쓰는 게 맞아.

git switch <branch>는 현재 branch를 바꾸고, git switch -c <branch>는 만들면서 옮겨가. git switch -cd -처럼 직전 branch로 돌아가고, git switch --detach <commit>는 의도적으로 detached HEAD 상태에 들어가. 옛 git checkout도 여전히 작동하고 오래된 문서에서 보게 되겠지만, 새 작업에는 switch를 우선해.

Detached HEAD는 HEAD가 branch 이름을 거치지 않고 commit을 직접 가리키는 상태야. 오류가 아니라 옛 commit을 살피거나 tagged release를 빌드할 때 유효한 상태지. 다만 이곳에서 만든 commit은 어느 branch에도 속하지 않아. 다른 곳으로 switch하면 orphan이 돼. 떠나기 전에 git switch -c rescue-branch를 실행하면 HEAD의 정확한 자리에 branch가 생겨 작업을 붙잡아줘.

switch하기 전에 Git은 작업 트리를 확인해. 옮겨가면서 commit하지 않은 변경을 덮어쓰게 된다면 명령을 거부하지. 이때는 현재 작업을 commit하거나 amend하고, 아직 commit할 때가 아니라면 git stash push -u로 stash해. git config --global advice.detachedHead false로 detached HEAD 안내를 숨기는 팀도 있지만, 뜻을 충분히 이해한 다음에만 써.

Code

현대적인 branch 전환·bash
# 기존 branch 로 switch
git switch feature/login

# 만들면서 switch
git switch -c feature/profile

# 이전 branch 로 점프
git switch -

# remote-tracking branch 로 switch (local tracking branch 자동 생성)
git switch feature/from-teammate

# 옛 동의어 (여전히 유효, 새 코드엔 switch):
git checkout feature/login
git checkout -b feature/profile
Detached HEAD: 안전 입장, 안전 탈출·bash
# branch 안 떠나고 옛 release 검사
git switch --detach v1.4.0
# HEAD 가 v1.4.0 commit 가리킴, branch 없음

# detached 상태에서 실험 commit 했어?
git log --oneline -5

# switch 떠나기 전에 anchor:
git switch -c rescue/v1.4-investigation

# 이미 떠났는데 tip 잃었어?
git reflog              # dangling commit 찾기
git switch -c rescue HEAD@{2}

External links

Exercise

branch가 둘이고 각 branch에 commit이 세 개 이상 있는 연습용 repo에서 git switch로 오가봐. 이어서 git switch --detach <old-commit>한 뒤 새 commit을 하나 만들어. git status가 HEAD에 대해 무엇을 말하는지 읽고 git switch -c experiment로 붙잡아. 새 commit이 새 branch 위에 있는지 확인한 다음, branch를 만들지 않고 떠났다면 어떻게 됐을지 두 줄로 적어.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.