Git stash 命令

有这么一个场景,你正在feat-create分支上开发一个功能模块,突然临时有一个紧急Bug需要修复,但是你正在开发的程序预计还有一天才能写完,而修复这个Bug只需要五分钟。这个时候git的stash功能就派上用场了。

stash命令表示储藏,就是把当前的工作先储藏起来,去干别的工作,完成后在取出之前储藏的工作继续工作。

【国内直连ChatGPT 29元起】
国内直连ChatGPT,Plus会员每月29元起,支持最新o1模型探索更多领域,无需注册OpenAI账号。

看看文档

NAME
  git-stash - Stash the changes in a dirty working directory away
  
SYNOPSIS
  git stash list [<options>]
  git stash show [<stash>]
  git stash drop [-q|--quiet] [<stash>]
  git stash ( pop | apply ) [--index] [-q|--quiet] [<stash>]
  git stash branch <branchname> [<stash>]
  git stash save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]
              [-u|--include-untracked] [-a|--all] [<message>]
  git stash [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]
              [-u|--include-untracked] [-a|--all] [-m|--message <message>]]
              [--] [<pathspec>...]]
  git stash clear
  git stash create [<message>]
  git stash store [-m|--message <message>] [-q|--quiet] <commit>

我们先储藏试一试,储藏特别简单,直接git stash即可

test1 git:feat-create ❯ git stash                                                                           ✹
Saved working directory and index state WIP on feat-create: f869af5 first

然后,我们可以使用git stash list查看储藏里有什么东西

git stash list
stash@{0}: WIP on feat-create: f869af5 first
(END)

我们看见了有一条储藏记录f869af5,然后我们checkout到master分支,然后在master分支上新创建一个分支,开始修复Bug

test1 git:feat-create ❯ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
test1 git:master ❯ git checkout -b bug-202
Switched to a new branch 'bug-202'

修复完后,你需要合并回master并删除这个分支

test1 git:bug-202 ❯ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
test1 git:master ❯ git merge --no-ff -m "merged bug fix 202" bug-202
Merge made by the 'recursive' strategy.
 CHANGELOG.md | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 CHANGELOG.md

然后,你需要取回之前的工作状态继续工作,取回命令git stash pop

test1 git:master ❯ git checkout feat-create
Switched to branch 'feat-create'
test1 git:feat-create ❯ git stash pop
On branch feat-create
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:   README.md

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

现在代码已恢复到之前的状态了,可以继续之前的工作了

分享

TITLE: Git stash 命令

LINK: https://www.qttc.net/96-git-stash.html

NOTE: 原创内容,转载请注明出自琼台博客