[TIL] Git 커밋 없이 Checkout 하면 어떤 일이 일어날까?

Jun·2021년 5월 2일
0

TIL

목록 보기
1/1

git으로 버젼관리를 하면서 프로젝트를 진행할 때 어떤 브랜치에서 작업하다가 다른 브랜치로 잠시 넘어가야 할 때가 있다.

문제는 해당 브랜치의 작업 내용이 아직 커밋하기도 애매하고 그렇다고 버리기도 애매할 때가 있다는 것.

Branch A에서 작업하다가 커밋하지 않은 내용이 있을 때 Branch B로 checkout하면 어떤 일이 일어날까?

git은 데이터 손실을 피하려 한다.

결론부터 말하자면 그냥 checkout시 git은 Branch A의 커밋되지 않은 변경사항을 체크아웃한 Branch B로 따라가져온다. 이는 git이 최대한 불필요한 데이터 손실을 피하고자 하기 위함이라고 한다.

$ echo "ADD 1" >> "test.md"

$ git add test.md

$ git commit -m "add 1"
[master (root-commit) a075fdb] add 1
 1 file changed, 1 insertion(+)
 create mode 100644 test.md

$ git branch branchA

$ git branch branchB

$ git checkout branchA
Switched to branch 'branchA'

$ echo "ADD 2 in BranchA" >> test.md

$ git status
On branch branchA
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
	modified:   test.md

no changes added to commit (use "git add" and/or "git commit -a")

$ cat test.md
ADD 1
ADD 2 in BranchA

$ git checkout branchB
M	test.md
Switched to branch 'branchB'

$ git status
On branch branchB
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
	modified:   test.md

no changes added to commit (use "git add" and/or "git commit -a")

$ cat test.md
ADD 1
ADD 2 in BranchA

checkout시 변경 사항을 버리고 가고 싶다면?

git checkout -f 명령으로 체크아웃시 변경사항을 버리고 브랜치를 바꿀 수 있다.

$ git status
On branch branchB
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
	modified:   test.md

no changes added to commit (use "git add" and/or "git commit -a")

$ git checkout -f master
Switched to branch 'master'

$ git status
On branch master
nothing to commit, working tree clean
profile
개발합니다.

0개의 댓글