在某些情况下,我想丢弃当前在暂存区域中的所有文件,并且仅丢弃当前在暂存区域中的文件。本质上,我想要的东西就像进行提交,然后立即丢弃刚刚进行的提交。
现在在实践中我主要使用 git stash
为此,请记住我实际上并不想要我 stash 的东西。
但是,stash
ing 和丢弃实际上并不是同一件事,stash
似乎捕获了所有跟踪的文件,而不仅仅是当前位于暂存区域的文件,如下面的脚本所示。
有没有办法完全丢弃(更改)当前暂存区域中的文件?
#!/bin/bash
mkdir -p ./a
echo foo > ./a/foo
echo bar > ./a/bar
(
# add initial commit
cd ./a
git init
git add foo
git add bar
git commit --message='initial commit'
# change first line of foo and bar
ed ./foo <<'EOF'
s/$/ aaaaaa/
wq
EOF
ed ./bar <<'EOF'
s/$/ aaaaaaa/
wq
EOF
git add ./foo
git stash save
git status
)
运行时,此脚本会产生以下输出
$ bash gitrepo.sh
Initialized empty Git repository in ~/git/a/a/.git/
[master (root-commit) a8f0104] initial commit
2 files changed, 2 insertions(+)
create mode 100644 bar
create mode 100644 foo
4
11
4
12
Saved working directory and index state WIP on master: a8f0104 initial commit
HEAD is now at a8f0104 initial commit
我还尝试了与 git clean -f
基本相同的脚本和git reset
代替git stash save
git clean -f
似乎没有放弃对 foo
的更改也不到bar
.
[master (root-commit) 0c10b47] initial commit
2 files changed, 2 insertions(+)
create mode 100644 bar
create mode 100644 foo
4
11
4
12
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: foo
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: bar
git reset
在这种特定情况下,似乎只是删除 foo
从暂存区。
[master (root-commit) 65fce7b] initial commit
2 files changed, 2 insertions(+)
create mode 100644 bar
create mode 100644 foo
4
11
4
12
Unstaged changes after reset:
M bar
M foo
到目前为止,我拥有的当前最佳解决方案是以下脚本,它在我测试过的少数情况下具有正确的行为。但是,它通过创建、提交然后删除由 UUID 命名的新分支来完成此行为。我更喜欢一种放弃暂存区域中的更改的不太迂回的方法。
#!/bin/bash
branch="$(python -c 'import uuid; print(str(uuid.uuid4()))')"
git checkout -b "$branch"
git commit -m "commit for $branch"
git checkout -
git branch -D "$branch"
当使用gitdiscard
时(上面的脚本),测试器脚本产生正确的结果,foo 的更改被丢弃,但对 bar
的未暂存修改还在那里。
[master (root-commit) e4e81d9] initial commit
2 files changed, 2 insertions(+)
create mode 100644 bar
create mode 100644 foo
4
11
4
12
M bar
M foo
Switched to a new branch 'abebe893-e579-4ecc-9422-6c99051d67f6'
[abebe893-e579-4ecc-9422-6c99051d67f6 05916d5] commit for abebe893-e579-4ecc-9422-6c99051d67f6
1 file changed, 1 insertion(+), 1 deletion(-)
M bar
Switched to branch 'master'
Deleted branch abebe893-e579-4ecc-9422-6c99051d67f6 (was 05916d5).
类似但不重复问题的非详尽列表:
This question不是重复,因为它指的是丢弃未跟踪的文件,而不是暂存区域中的更改。
This question不是重复,因为它指的是直接清除整个工作,而不是丢弃暂存区的更改。
This question涵盖未跟踪的文件和未跟踪的目录,但不包括放弃对暂存区域中文件的更改。
最佳答案
您可以考虑 --keep-index
git stash
事实上,它的作用与您所要求的相反:它存储了除了索引中的所有内容。
您可以利用这一点并仅存储未暂存的更改,然后重置索引和工作树,最后重新应用存储。
(我不确定您希望如何处理未跟踪的文件,但也可以记住存储标志 --include-untracked
。将其用于如果您需要将它们包含在最终结果中,请首先 stash )
git stash --keep-index [--include-untracked]
git reset --hard
git stash apply
关于git丢弃专门更改暂存区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58497639/