如何在我的分支中只存储多个已更改文件中的一个?


当前回答

git add .                           //stage all the files
git reset <pathToFileWillBeStashed> //unstage file which will be stashed
git stash                           //stash the file(s)
git reset .                         // unstage all staged files
git stash pop                       // unstash file(s)

其他回答

VonC将文件复制到Git存储库外部的“中间”解决方案的问题是,您会丢失路径信息,这使得稍后将一堆文件复制回来有些麻烦。

A发现使用tar(类似的工具可能会这样做)而不是复制更容易:

tar cvf/tmp/stash.tar路径/to/some/file路径/to/some/other/file(…等)git签出路径/to/some/file-path/to/some/other/file暂存tar xvf/tmp/stash.tar等等(见VonC的“中间”建议)

对于VS代码的用户。Git侧边栏视图中Changes组的隐藏按钮将仅隐藏组中的文件。因此,如果您将一些文件移出该组,则可以隐藏其余文件。我所知道的在不恢复更改的情况下将一些文件移出的唯一方法是将它们暂存。因此:

暂存您不想隐藏的文件单击更改组标题中的隐藏按钮取消对您移开的文件的分级

git stash push -p -m "my commit message"

-p让我们选择应该隐藏的大块;也可以选择整个文件。

系统将提示您对每个大块执行一些操作:

   y - stash this hunk
   n - do not stash this hunk
   q - quit; do not stash this hunk or any of the remaining ones
   a - stash this hunk and all later hunks in the file
   d - do not stash this hunk or any of the later hunks in the file
   g - select a hunk to go to
   / - search for a hunk matching the given regex
   j - leave this hunk undecided, see next undecided hunk
   J - leave this hunk undecided, see next hunk
   k - leave this hunk undecided, see previous undecided hunk
   K - leave this hunk undecided, see previous hunk
   s - split the current hunk into smaller hunks
   e - manually edit the current hunk
   ? - print help

由于在Git中创建分支很简单,您可以创建一个临时分支并将各个文件检入其中。

解决方案

本地更改:

file_A(已修改)未暂存file_B(已修改)未暂存file_C(已修改)未暂存

要创建仅包含file_C上的更改的存储“my_stash”:

1. git add file_C
2. git stash save --keep-index temp_stash
3. git stash save my_stash
4. git stash pop stash@#{1}

完成。


解释

将file_C添加到临时区域创建一个名为“temp_stash”的临时存储,并将更改保存在file_C上只使用file_C上的更改创建所需的存储(“my_stash”)将“temp_stash”(file_A和file_B)中的更改应用于本地代码并删除存储

您可以在步骤之间使用gitstatus来查看发生了什么。