當手頭工作沒有完成時,先把工作現(xiàn)場git stash一下,然后去修復bug,修復后,再git stash pop,回到工作現(xiàn)場。
當你接到一個修復一個代號101的bug的任務時,很自然地,你想創(chuàng)建一個分支issue-101來修復它,但是,等等,當前正在dev上進行的工作還沒有提交:
git status
------------------------------------
# On branch dev
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: hello.py
#
# 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: readme.txt
#
并不是你不想提交,而是工作只進行到一半,還沒法提交,預計完成還需1天時間。但是,必須在兩個小時內(nèi)修復該bug,怎么辦?
Git還提供了一個stash功能,可以把當前工作現(xiàn)場“儲藏”起來,等以后恢復現(xiàn)場后繼續(xù)工作:
git stash
現(xiàn)在,用git status查看工作區(qū),就是干凈的,因此可以放心地創(chuàng)建分支來修復bug。
首先確定要在哪個分支上修復bug,假定需要在master分支上修復,就從master創(chuàng)建臨時分支:
git checkout master
git checkout -b issue-101
現(xiàn)在修復bug,需要把“Git is free software ...”改為“Git is a free software ...”,然后提交:
git add .
git commit -m '修復完成'
修復完成后,切換到master分支,并完成合并,最后刪除issue-101分支:
git checkout master
git merge --no-ff -m '修復完成-合并' issue-101
git branch -d issue-101
太棒了,原計劃兩個小時的bug修復只花了5分鐘!現(xiàn)在,是時候接著回到dev分支干活了!
git checkout dev
git status
工作區(qū)是干凈的,剛才的工作現(xiàn)場存到哪去了?用git stash list命令看看
git stash list
工作現(xiàn)場還在,Git把stash內(nèi)容存在某個地方了,但是需要恢復一下,有兩個辦法
一是用git stash apply恢復,但是恢復后,stash內(nèi)容并不刪除,你需要用git stash drop來刪除;
另一種方式是用git stash pop,恢復的同時把stash內(nèi)容也刪了
git stash pop
你可以多次stash,恢復的時候,先用git stash list查看,然后恢復指定的stash,用命令
git stash apply stash@{0}