C.W.K.
Stream
Lesson 02 of 05 · published

git switch, checkout, detached HEAD

~20 min · switch, checkout, head

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

switch 는 modern 동사, checkout 은 overload 됨

수년간 git checkout 은 완전히 다른 두 일을 했어: branch switch + history 에서 파일 복원. 이 overload 가 입문자 실수의 단골 원인 — git checkout file.js 를 '파일 열기' 로 잘못 알고 쳐서 uncommitted 편집을 통째로 날리는 식. Git 2.23 (2019) 이 이걸 git switch (branch) 와 git restore (파일) 로 쪼갰어. 새 명령들이 더 명확하고 안전 — 모든 현대 가이드가 이걸 써야 해.

git switch <branch> 가 현재 branch 변경. git switch -c <branch> 는 만들면서 switch. git switch - 는 이전 branch 로 점프 (cd - 처럼). git switch --detach <commit> 는 일부러 detached HEAD 진입. 옛 git checkout 도 여전히 작동하고 옛 가이드에서 볼 거야, 새 코드엔 switch 선호.

Detached HEAD 는 HEAD 가 branch 이름이 아니라 commit 에 직접 가리키는 상태야. 에러 아니야 — 옛 commit 검사나 tagged release 빌드용으로 유효한 상태. 위험: 그 상태에서 만든 commit 은 어떤 branch 에도 안 속해. 다른 데로 switch 하면 orphan 돼. 탈출구: detached commit 에서 git switch -c rescue-branch 하면 HEAD 가 있는 정확히 그 자리에 branch 가 생겨 작업이 anchor 돼.

switch 하기 전에 Git 이 working tree 를 확인해. switch 가 uncommitted 변경 덮어쓸 거면 거부해. 깔끔한 두 반응: 가진 거 commit (또는 amend), 아니면 stash (git stash push -u). 일부 팀은 git config --global advice.detachedHead false 로 detached-HEAD 안내문 silence — 이해한 다음에만.

Code

Modern branch switching·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 두 개 + 각자 commit 세 개 이상 있는 scratch repo 에서 git switch 로 왔다갔다. 그 다음 git switch --detach <old-commit>, 새 commit 하나. git status 가 HEAD 에 대해 뭐라 하는지 읽어. git switch -c experiment 로 anchor. 새 commit 이 새 branch 위에 있는지 확인. anchor 없이 떠났다면 어떻게 됐을지 두 줄로 적어.

Progress

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

댓글 0

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

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