git unstash详解
在日常开发中,我们经常会需要在切换分支之前暂存当前的工作进度,以便在未来可以方便地恢复。这时就可以使用git stash
命令将当前的变动存储起来。但有时候我们可能会忘记在切换分支前恢复我们之前暂存的工作进度,这时就需要使用git unstash
命令来恢复暂存的工作进度。
1. 什么是git stash
在解释git unstash
命令之前,先来了解一下什么是git stash
。
当我们在开发过程中需要暂存当前的工作状态,但又不想提交到版本库中时,可以使用git stash
命令。这个命令会将当前工作目录中的所有未暂存内容(包括已经跟踪的和未跟踪的文件)保存到一个特殊的堆栈中,并把工作目录恢复到最近的一次提交状态。
2. git stash的基本用法
git stash
命令的基本用法如下:
git stash
这个命令会将当前的工作进度保存到一个栈中,并且将工作目录恢复到最近的一次提交状态。如果有未暂存的改动,也会一并保存。
如果想在stash的同时添加一些注释,可以使用git stash save
命令:
git stash save "my work in progress"
这个命令会把当前的工作进度保存到栈中,并且添加一条注释,方便以后查看。
3. git unstash的基本用法
git unstash
命令用来恢复之前暂存的工作进度。其基本用法如下:
git stash apply
这个命令会恢复最近一次暂存的工作进度,并且会保留暂存的记录在堆栈中。
如果不想保留暂存的记录,可以使用下面的命令:
git stash pop
这个命令会恢复最近一次暂存的工作进度,并且会将此次暂存从栈中移除。
4. 使用示例
接下来通过一个示例来演示如何使用git stash
和git unstash
命令。
假设我们有一个项目,目前有两个文件:file1.txt
和file2.txt
。我们对file1.txt
做了修改,但还没有提交。我们首先使用git status
来查看状态:
$ 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: file1.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
file2.txt
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: 308d19d my work in progress
接着我们对file1.txt
进行另外一些修改,并检查状态:
$ echo "new line" >> file1.txt
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
file2.txt
no changes added to commit (use "git add" and/or "git commit -a")
现在我们想把之前暂存的工作进度恢复,可以使用git stash apply
命令:
$ git stash apply
再次查看状态:
$ 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: file1.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
file2.txt
no changes added to commit (use "git add" and/or "git commit -a")
可以看到file1.txt
中的修改被成功恢复了。
最后,如果我们想要将之前暂存的工作进度取出并移除暂存记录,可以使用git stash pop
命令:
$ git stash pop
5. 总结
git stash
和git unstash
是在日常开发中非常有用的命令,可以帮助我们在不同分支之间切换时暂存和恢复工作进度。使用这两个命令可以更加灵活地管理我们的工作进度,提高开发效率。