생활코딩 git 06 - git stash, git stash apply, git stash pop

|

생활코딩-git 수업을 듣고 중요 내용을 정리합니다.

git stash

다른 브랜치로 checkout을 해야 하는데 아직 현재 브랜치에서 작업이 끝나지 않은 경우는 커밋을 하기가 애매합니다. 이런 경우 stash를 이용하면 작업중이던 파일을 임시로 저장해두고 현재 브랜치의 상태를 마지막 커밋의 상태로 초기화 할 수 있습니다. 그 후에 다른 브랜치로 이동하고 작업을 끝낸 후에 작업 중이던 브랜치로 복귀한 후에 이전에 작업하던 내용을 복원할 수 있습니다. 여기서는 이 기능에 대해서 알아봅니다.

git stash 의 기능

  • stash : 감추다, 숨겨두다
  • branch를 이용하여 활발하게 작업을 하다보면, branch 작업이 완료되지 않은 상태에서 다른 branch 로 checkout 해야 하는 상황이 발생한다.
  • 이럴때 아직 작업중인 파일을 commit을 하기도 곤란하고, commit을 하지 않으면 checkout이 어려운 상황이 발생한다.
  • 그런 경우에 stash를 사용하여 작업중인 파일을 숨겨둘 수 있다.

예시 1 - 문제상황

# master 브랜치
❯ vim f1.txt # 파일 내용 수정
❯ git add f1.txt
❯ git commit -m 1

# exp 브랜치
❯ git checkout -b exp # exp 브랜치를 만들고 체크아웃
❯ vim f1.txt # 파일 내용 수정후, add commit을 진행하지 않고 master로 체크아웃

# master 브랜치
❯ git checkout master
❯ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   f1.txt # exp 브랜치에서 수정중인 내용이 master에도 영향을 미침

예시 2 - git stash 활용

  • 아직 파일의 수정이 끝나지 않아서 commit 하기가 곤란하고, 다른 branch로 checkout을 하기도 곤란한 상황을 처리할 때 git stash를 사용
  • git stash 명령은 최소한 버전관리가 되고 있는 파일에 대해서만 수행이 가능하다. (= git add를 통해서 트래킹 중인 파일)
  • WIP(working in process)
# exp 브랜치
❯ git stash
Saved working directory and index state WIP on exp: ba5adba 1
HEAD is now at ba5adba 1

❯ git status
On branch exp
nothing to commit, working tree clean

# master 브랜치
❯ git checkout master
❯ git status
On branch master
nothing to commit, working tree clean

예시 3 - git stash apply 활용

  • git stash 를 통해서 숨겼던 수정중 파일의 상태를 원상태로 복구
❯ git stash apply
On branch exp
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   f1.txt

no changes added to commit (use "git add" and/or "git commit -a")
  • git reset –hard를 통해서 가장 최신 commit 상태로 working space 상태를 변경한다. (commit 하지 않은 수정중인 파일 내용을 삭제)
  • git stash apply 를 통해서 수정 내용을 복구할 수 있다.
  • stash list에 나오는 리스트는 명시적으로 삭제하지 않는 이상, 항상 살아있다.
  • git stash drop을 통해 최신 stash 삭제가 가능하다.
❯ git reset --hard HEAD # 최신 commit으로 reset (변경중인 파일 내용 삭제)

❯ git stash list
stash@{0}: WIP on exp: ba5adba 1 # 가장 최신의 stash 내용
stash@{1}: WIP on exp: ba5adba 1
stash@{2}: WIP on exp: ba5adba 1

❯ git stash apply # 가장 최신의 stash 내용으로 다시 복원
On branch exp
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   f1.txt

❯ git stash drop # 가장 최신 stash 삭제
❯ git stash apply; git stash drop; # stash 복원 및 삭제
❯ git stash pop # stash 복원 및 삭제 (상기명령 동일)