我对一个文件进行了更改,再加上一个新文件,我想在切换到另一个任务时使用git stash将它们保存起来。但是git stash本身只存储对现有文件的更改;新文件仍保留在我的工作树中,打乱了我未来的工作。我如何保存这个未跟踪的文件?


当前回答

我认为这可以通过告诉git文件存在来解决,而不是将文件的所有内容提交到暂存区,然后调用git stash。Araqnid描述了如何实现前者。

git add --intent-to-add path/to/untracked-file

or

git update-index --add --cacheinfo 100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 path/to/untracked-file

然而,后者不起作用:

$ git stash
b.rb: not added yet
fatal: git-write-tree: error building trees
Cannot save the current index state

其他回答

从git1.7.7开始,gitstash接受--include未跟踪选项(或短手-u)。要将未跟踪的文件包含在存储库中,请使用以下任一命令:

git stash --include-untracked
# or
git stash -u

警告:如果您的gitignore文件中有任何目录/条目,那么这样做将永久删除您的文件*

将文件添加到索引:

git add path/to/untracked-file
git stash

索引的全部内容,加上对现有文件的任何未标记的更改,都将被放入存储库。

我在对新创建的文件使用Sourcetree时遇到了类似的问题(它们也不会包含在存储库中)。

当我第一次选择“stage all”,然后将新添加的组件隐藏在跟踪的位置,因此包含在隐藏中。

您只需使用以下命令即可完成

git stash save --include-untracked

or

git stash save -u

有关git stash的更多信息,请访问此帖子(单击此处)

这里有几个正确的答案,但我想指出,对于新的整个目录,“git-add-path”将不起作用。因此,如果您在未跟踪的路径中有一堆新文件,请执行以下操作:

git add untracked-path
git stash "temp stash"

这将隐藏以下消息:

Saved working directory and index state On master: temp stash
warning: unable to rmdir untracked-path: Directory not empty

如果未追踪的路径是你隐藏的唯一路径,那么“临时隐藏”将是一个空的隐藏。正确的方法是添加整个路径,而不仅仅是目录名(即以“/”结束路径):

git add untracked-path/
git stash "temp stash"