是否有一个git stash
命令可以将您的更改存储,但同时保留它们在工作目录中?因此,基本上是一步完成 git stash; git stash apply
的操作吗?
值得一提的是,另一种做法是先暂存你想要保留的更改,然后使用 --keep-index
参数来暂存所有更改:
$ git add modified-file.txt
$ git stash push --keep-index
以上命令将隐藏所有更改,但会保留文件在您的工作目录中。
来自官方Linux内核Git文档git stash
或者 git-scm:
如果使用
--keep-index
选项,则所有已添加到索引的更改都将被保留不变。
git add --all
命令即可。 - mfaanigit stash push --keep-index -m "message"
,但它仍然清空了工作目录!然后我又清空了工作目录的更改,因为我以为我已经修改并保存了旧文件,然后应用了stash,结果发现并不是所有我之前有的文件都在stash中,而且现在都消失了! - Mark Jeronimusgit add
进行暂存。 - VishnuVSgit stash
然后 git stash apply
(git stash && git stash apply
)将会把文件存储并立即应用。所以最终你将会在存储中拥有你的更改,同时也会在工作目录中。
如果想要一步到位,可以创建一个别名。只需将以下内容放入~/.gitconfig
:
[alias]
sta = "!git stash && git stash apply"
这种方法的缺点是所有文件都会被储藏并重新创建。这意味着相关文件的时间戳将会改变。(在我执行了git sta
之前打开文件的话,这会导致Emacs发出警告并要求保存文件,并且如果你正在使用make
或类似工具,可能会导致不必要的重建。)
这种方法的缺点是所有文件都会被暂存和重新创建。这意味着相关文件的时间戳将会被更改。(如果在执行git sta
之前已经打开了文件,这会导致Emacs警告我在保存文件时进行更改,并且如果您正在使用make
或类似工具,则可能会导致不必要的重建。)
git config --global alias.sta "!git stash && git stash apply"
就可以了。 - user456814您可以使用git stash create
创建一个暂存提交,然后使用git stash store
将其保存到暂存区中:
git stash store $(git stash create) -m "Stash commit message"
这可以保存到 git 别名中,以使其更方便:
git config --global alias.stash-keep '!git stash store $(git stash create)'
git stash-keep -m "Stash commit message"
请注意,这并不做git stash push所做的所有事情。例如,它不会将分支名称附加到提交中,例如“stash@{0}:On myBranch:Stash commit message
”。
man git-stash
说 -m <message>
必须在提交哈希之前。除非在最新的 Git 中有所改变。 - taniussave = "!f() { git stash store $(git stash create); }; f"
这个命令,它起作用了。 - jasongregorigit stash list
正确显示它。 - Jannes这是一个小的增强,实际应用中可能会经常使用。
$ git add modified-file.txt
(OR $ git add . ---- for all modified file)
$ git stash save --keep-index "Your Comment"
git commit -m "Your already staged content (May be empty)" #(Commit index)
git add -A #(stage remaining 'unstaged' contents)
git commit -m "My works so far (Unstaged)" #(Working directory)
git tag stash #(mark the commit with 'stash' tag)
git reset HEAD^ #(1st reset (--mixed): Unstaged)
git reset --soft HEAD^ #(2nd reset (--soft): Staged (Skip if your index was empty))
现在你有一个标记为stash的提交,无法执行git stash pop
,但你可以从创建的“stash”标签中执行其他操作,比如创建补丁或重置文件等,你的工作目录文件也会保持不变。
current_branch=`git branch --show-current`
git checkout -b stash #(create and switch to new branch 'stash')
git commit -m "Your already staged content (May be empty)" #(Commit index)
git add -A #(stage remaining 'unstaged' contents)
git commit -m "My works so far (Unstaged)" #(Working directory)
git reset HEAD^ #(1st reset (--mixed): Unstaged)
git reset --soft $current_branch #(2nd reset (--soft): Staged)
git checkout $current_branch #(Now go back to where you've left with your working dir and staged status intact)
reset
命令的 --soft
选项。我已经更新了我的答案。 - KenIchi
git stash && git stash apply
的方法。您会注意到,那个问题的答案与我的相当不同。 - Michael Dorst