git checkout과 switch

한 줄 요약

브랜치를 전환하거나 특정 커밋으로 이동

선행 지식

switch vs checkout

Git 2.23부터 checkout의 기능이 분리되었습니다:

명령어용도Git 버전
git switch브랜치 전환 전용2.23+
git restore파일 복원 전용2.23+
git checkout둘 다 (기존 방식)모든 버전

권장사항

가능하면 switchrestore를 사용하세요. 더 명확하고 안전합니다.

기본 사용법

브랜치 전환

# switch (권장)
git switch 브랜치명
 
# checkout (기존)
git checkout 브랜치명

브랜치 생성 + 전환

# switch (권장)
git switch -c 새브랜치명
 
# checkout (기존)
git checkout -b 새브랜치명

주요 옵션

git switch 옵션

옵션설명예시
(없음)브랜치 전환git switch main
-c생성 + 전환git switch -c feature
-C강제 생성 + 전환git switch -C feature
-이전 브랜치로git switch -
--detachDetached HEAD로git switch --detach a1b2c3d

git checkout 옵션

옵션설명예시
(없음)브랜치 전환git checkout main
-b생성 + 전환git checkout -b feature
-B강제 생성 + 전환git checkout -B feature
-이전 브랜치로git checkout -

실제 예제

브랜치 전환

# main 브랜치로 전환
$ git switch main
Switched to branch 'main'
 
# 현재 브랜치 확인
$ git branch
  develop
* main

새 브랜치 생성 + 전환

# feature/login 브랜치 생성하고 전환
$ git switch -c feature/login
Switched to a new branch 'feature/login'

이전 브랜치로 돌아가기

$ git switch main       # main으로
$ git switch develop    # develop으로
$ git switch -          # 다시 main으로 (이전 브랜치)

특정 커밋으로 이동 (Detached HEAD)

# switch 사용
git switch --detach a1b2c3d
 
# checkout 사용
git checkout a1b2c3d

Detached HEAD

특정 커밋으로 이동하면 브랜치가 아닌 상태가 됩니다. 이 상태에서 커밋하면 나중에 찾기 어려울 수 있습니다. → Detached HEAD 상태 참고

특정 커밋에서 새 브랜치 생성

# a1b2c3d 커밋에서 새 브랜치 시작
git switch -c hotfix a1b2c3d

전환 전 변경사항 처리

커밋되지 않은 변경이 있을 때

$ git switch main
error: Your local changes to the following files would be overwritten by checkout:
        app.js
Please commit your changes or stash them before you switch branches.

해결 방법 1: 커밋

git add .
git commit -m "WIP: 작업 중"
git switch main

해결 방법 2: Stash

git stash                # 임시 저장
git switch main          # 브랜치 전환
# ... 작업 ...
git switch feature       # 돌아와서
git stash pop            # 복원

해결 방법 3: 강제 전환 (⚠️ 변경 폐기)

git switch -f main      # 변경사항 버리고 전환
# 또는
git checkout -f main

원격 브랜치 체크아웃

# 원격 브랜치를 로컬로 가져오면서 전환
git switch -c feature origin/feature
 
# 또는 자동으로 추적
git switch feature
# 'origin/feature'를 추적하는 'feature' 브랜치 생성

checkout의 파일 복원 기능 (비권장)

checkout은 파일 복원에도 사용할 수 있지만, restore를 권장합니다:

# checkout 방식 (혼란스러움)
git checkout -- app.js
 
# restore 방식 (명확함, 권장)
git restore app.js

git restore 참고

자주 하는 실수

브랜치와 파일 이름이 같을 때

$ git checkout feature
# 브랜치? 파일?

해결:

git switch feature       # 브랜치 (명확)
git restore feature      # 파일 (명확)
git checkout -- feature  # 파일 (기존 방식)

변경사항 있는 상태에서 전환 실패

위의 “전환 전 변경사항 처리” 섹션 참고

관련 명령어

더 알아보기