Git隱藏(Stash)操作


假設您正在為產品新的功能編寫/實現程式碼,當正在編寫程式碼時,突然出現軟體用戶端升級。這時,您必須將新編寫的功能程式碼保留幾個小時然後去處理升級的問題。在這段時間內不能提交程式碼,也不能丟棄您的程式碼更改。 所以需要一些臨時等待一段時間,您可以儲存部分更改,然後再提交它。

在Git中,隱藏操作將使您能夠修改跟蹤檔案,階段更改,並將其儲存在一系列未完成的更改中,並可以隨時重新應用。

$ git status
On branch master
Your branch is up-to-date with 'origin/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:   main.py

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

現在,要切換分支以進行客戶升級,但不想提交一直在做的工作; 那麼可以把當前工作的改變隱藏起來。 要將一個新的存根推到堆疊上,執行git stash命令。

$ git stash
Saved working directory and index state WIP on master: ef07ab5 synchronized with the remote repository
HEAD is now at ef07ab5 synchronized with the remote repository

現在,工作目錄是乾淨的,所有更改都儲存在堆疊中。 現在使用git status命令來檢視當前工作區狀態。

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

nothing to commit, working directory clean

現在,可以安全地切換分支並在其他地方工作。通過使用git stash list命令來檢視已存在更改的列表。

$ git stash list
stash@{0}: WIP on master: ef07ab5 synchronized with the remote repository

假設您已經解決了客戶升級問題,想要重新開始新的功能的程式碼編寫,查詢上次沒有寫完成的程式碼,只需執行git stash pop命令即可從堆疊中刪除更改並將其放置在當前工作目錄中。

$ git status -s

Administrator@MY-PC /D/worksp/sample (master)

[jerry@CentOS project]$ git stash pop

上述命令將產生以下結果:

$ git stash pop
On branch master
Your branch is up-to-date with 'origin/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:   main.py

no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (e713780380632c142ed5833a9087aca883a826fa)

Administrator@MY-PC /D/worksp/sample (master)

$ git status
On branch master
Your branch is up-to-date with 'origin/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:   main.py

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

可以看到,工作區中修改的檔案(main.py)又顯示了。現在我們就可以繼續編寫上次編寫了未完成的程式碼。