git stash 用法总结分析
在git使用中,我们可能会面临以下几种情况。
- pull代码之前,需要把已修改文件暂存。
- pull代码的时候遇到和工作区修改的文件冲突情况,为了避免拉取冲突,需要把已修改文件暂存,pull之后再解决冲突;
- 在功能开发过程中,遇到急需修复的bug,需要修改的文件可能和现在开发的相同,需要将已经开发的内容暂存,使正常开发和bug修复隔离,然后进行bug修复,修复完提交。
git stash的作用是把修改的文件暂存到本地,将工作区文件还原至上次git更新、提交时的状态。新增文件不能暂存,也不会被删除。
git stash
先来看下当前 git
工作区的状态
$ git status
On branch dev
Your branch is up to date with 'origin/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: app/controller/login.ts
modified: app/controller/user.ts
modified: app/middleware/jwtHandler.ts
modified: app/service/user.ts
Untracked files:
(use "git add <file>..." to include in what will be committed)
gitTest.ts
no changes added to commit (use "git add" and/or "git commit -a")
可以发现本地有四个文件被修改过,gitTest.ts
文件没有在Git版本控制中,是新增的文件,执行 git stash
$ git stash
Saved working directory and index state WIP on dev: f4d0a85 chore: 注释测试代码
该命令把工作区修改的文件保存起来,并将工作区恢复至上次git操作的状态,再次使用 git status
$ git status
On branch dev
Your branch is up to date with 'origin/dev'.
Untracked files:
(use "git add <file>..." to include in what will be committed)
gitTest.ts
nothing added to commit but untracked files present (use "git add" to track)
可以发现工作区里gitTest.ts文件是Untracked
状态,说明 git stash
不能保存新增的文件,其余四个被修改过的文件被保存,工作区恢复上次git代码更改时的状态