正如在其他地方所说,答案是git add 文件。例如:
git add path/to/untracked-file
git stash
但是,另一个答案中也提出了这个问题:如果您真的不想添加文件怎么办?好吧,据我所知,你必须这样做。以下将不工作:
git add -N path/to/untracked/file # note: -N is short for --intent-to-add
git stash
这会失败,如下:
path/to/untracked-file: not added yet
fatal: git-write-tree: error building trees
Cannot save the current index state
那么,你能做什么?好吧,您必须真正添加文件,然而,您可以稍后使用git rm --cached 有效地取消添加它:
git add path/to/untracked-file
git stash save "don't forget to un-add path/to/untracked-file" # stash w/reminder
# do some other work
git stash list
# shows:
# stash@{0}: On master: don't forget to un-add path/to/untracked-file
git stash pop # or apply instead of pop, to keep the stash available
git rm --cached path/to/untracked-file
然后您可以继续工作,以与git add 之前相同的状态(即使用名为path/to/untracked-file 的未跟踪文件;加上您可能必须对跟踪文件进行的任何其他更改)。
另一种可能的工作流程是这样的:
git ls-files -o > files-to-untrack
git add `cat files-to-untrack` # note: files-to-untrack will be listed, itself!
git stash
# do some work
git stash pop
git rm --cached `cat files-to-untrack`
rm files-to-untrack
[注意:正如@mancocapac 的评论中所述,您可能希望将--exclude-standard 添加到git ls-files 命令中(因此,git ls-files -o --exclude-standard)。]
... 这也可以很容易地编写脚本——即使是别名也可以(以 zsh 语法呈现;根据需要进行调整)[另外,我缩短了文件名,因此它完全适合屏幕,而无需在此答案中滚动;随意替换您选择的备用文件名]:
alias stashall='git ls-files -o > .gftu; git add `cat .gftu`; git stash'
alias unstashall='git stash pop; git rm --cached `cat .gftu`; rm .gftu'
请注意,后者可能更适合作为 shell 脚本或函数,以允许将参数提供给 git stash,以防您不希望 pop 而希望 apply,和/或希望能够指定一个特定的存储,而不是只取顶部的存储。也许这个(而不是上面的第二个别名)[空白被剥离以适应不滚动;重新添加以提高可读性]:
function unstashall(){git stash "${@:-pop}";git rm --cached `cat .gftu`;rm .gftu}
注意:在这种形式中,如果要提供存储标识符,则需要提供操作参数以及标识符,例如unstashall apply stash@{1} 或 unstashall pop stash@{1}
您当然会在 .zshrc 或等效项中添加哪个以长期存在。
希望这个答案对某人有所帮助,将所有内容放在一个答案中。