什麼是 Stashing

在處理專案時,當針對 master 生成錯誤時,你可能會在功能分支更改的中途完成。你尚未準備好提交程式碼,但你也不想丟失更改。這是 git stash 派上用場的地方。

在分支上執行 git status 以顯示未提交的更改:

(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:   business/com/test/core/actions/Photo.c

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

然後執行 git stash 將這些更改儲存到堆疊:

(master) $ git stash
Saved working directory and index state WIP on master: 
2f2a6e1 Merge pull request #1 from test/test-branch
HEAD is now at 2f2a6e1 Merge pull request #1 from test/test-branch

如果你已將檔案新增到工作目錄,則這些檔案也可以儲存。你只需要先安排它們。

(master) $ git stash
Saved working directory and index state WIP on master:
(master) $ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

        NewPhoto.c

nothing added to commit but untracked files present (use "git add" to track)
(master) $ git stage NewPhoto.c
(master) $ git stash
Saved working directory and index state WIP on master:
(master) $ git status
On branch master
nothing to commit, working tree clean
(master) $

你的工作目錄現在已清除你所做的任何更改。你可以通過重新執行 git status 來看到這個:

(master) $ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean

要應用最後一個儲存,請執行 git stash apply(此外,你可以應用刪除最後一個用 git stash pop 更改的儲存):

(master) $ git stash apply
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:   business/com/test/core/actions/Photo.c

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

但請注意,儲存不記得你正在處理的分支。在上面的例子中,使用者正在使用 master 。如果他們切換到 dev 分支, dev ,並執行 git stash apply,則最後一個儲存被放在 dev 分支上。

(master) $ git checkout -b dev
Switched to a new branch 'dev'
(dev) $ git stash apply
On branch dev
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:   business/com/test/core/actions/Photo.c

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