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


当前回答

另一种方法是:

# Save everything
git stash 

# Re-apply everything, but keep the stash
git stash apply

git checkout <"files you don't want in your stash">

# Save only the things you wanted saved
git stash

# Re-apply the original state and drop it from your stash
git stash apply stash@{1}
git stash drop stash@{1}

git checkout <"files you put in your stash">

在我(再次)来到这个页面并不喜欢前两个答案(第一个答案只是不回答问题,我不太喜欢使用-p交互模式)之后,我想到了这个问题。

这一想法与@VonC建议的使用存储库外的文件相同,您可以将所需的更改保存在某个位置,删除存储库中不需要的更改,然后重新应用您移开的更改。然而,我使用了git隐藏作为“某处”(因此,最后还有一个额外的步骤:移除你放在隐藏中的cahnges,因为你也把它们移到了一边)。

其他回答

使用git存储推送,如下所示:

git stash push [--] [<pathspec>...]

例如:

git stash push -- my/file.sh

这是自2017年春季发布的Git 2.13以来提供的。

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

一个复杂的方法是首先提交所有内容:

git add -u
git commit // creates commit with sha-1 A

重置回原始提交,但从新提交中签出_one_file:

git reset --hard HEAD^
git checkout A path/to/the_one_file

现在,您可以存储_one_file:

git stash

通过将提交的内容保存在文件系统中并重置为原始提交来进行清理:

git reset --hard A
git reset --soft HEAD^

是的,有点尴尬。。。

有时,我在提交分支之前对其进行了不相关的更改,我想将其移动到另一个分支并单独提交(如master)。我这样做:

git stash
git checkout master
git stash pop
git add <files that you want to commit>
git commit -m 'Minor feature'
git stash
git checkout topic1
git stash pop
...<resume work>...

请注意,第一个stash和stash pop可以取消,您可以在结账时将所有更改转移到主分支,但前提是没有冲突。此外,如果您要为部分更改创建新分支,则需要隐藏。

假设没有冲突和新分支,您可以简化它:

git checkout master
git add <files that you want to commit>
git commit -m 'Minor feature'
git checkout topic1
...<resume work>...

甚至不需要Stash。。。

解决方案

本地更改:

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来查看发生了什么。