• git stash

    git stash

    git stash命令用于暂时保存没有提交的工作。运行该命令后,所有没有commit的代码,都会暂时从工作区移除,回到上次commit时的状态。

    它处于git reset --hard(完全放弃还修改了一半的代码)与git commit(提交代码)命令之间,很类似于“暂停”按钮。

    1. # 暂时保存没有提交的工作
    2. $ git stash
    3. Saved working directory and index state WIP on workbranch: 56cd5d4 Revert "update old files"
    4. HEAD is now at 56cd5d4 Revert "update old files"
    5. # 列出所有暂时保存的工作
    6. $ git stash list
    7. stash@{0}: WIP on workbranch: 56cd5d4 Revert "update old files"
    8. stash@{1}: WIP on project1: 1dd87ea commit "fix typos and grammar"
    9. # 恢复某个暂时保存的工作
    10. $ git stash apply stash@{1}
    11. # 恢复最近一次stash的文件
    12. $ git stash pop
    13. # 丢弃最近一次stash的文件
    14. $ git stash drop
    15. # 删除所有的stash
    16. $ git stash clear

    上面命令会将所有已提交到暂存区,以及没有提交的修改,都进行内部保存,没有将工作区恢复到上一次commit的状态。

    使用下面的命令,取回内部保存的变化,它会与当前工作区的代码合并。

    1. $ git stash pop

    这时,如果与当前工作区的代码有冲突,需要手动调整。

    git stash命令可以运行多次,保存多个未提交的修改。这些修改以“先进后出”的stack结构保存。

    git stash list命令查看内部保存的多次修改。

    1. $ git stash list
    2. stash@{0}: WIP on new-feature: 5cedccc Try something crazy
    3. stash@{1}: WIP on new-feature: 9f44b34 Take a different direction
    4. stash@{2}: WIP on new-feature: 5acd291 Begin new feature

    上面命令假设曾经运行过git stash命令三次。

    git stash pop命令总是取出最近一次的修改,但是可以用git stash apply指定取出某一次的修改。

    1. $ git stash apply stash@{1}

    上面命令不会自动删除取出的修改,需要手动删除。

    1. $ git stash drop stash@{1}

    git stash 子命令一览。

    1. # 展示目前存在的stash
    2. $ git stash show -p
    3. # 切换回stash
    4. $ git stash pop
    5. # 清除stash
    6. $ git stash clear

    参考链接

    • Ryan Hodson, Quick Tip: Leveraging the Power of Git Stash