23

In git, is there any (simple) way to modify the index so that only changes to files which are already in it are added? It sounds kind of complicated, but what I want to achieve is simple.

Lets say my index looks like this (slightly stripped git status output):

# Changes to be committed:
#       modified:   A
#       modified:   B
#
# Changed but not updated:
#       modified:   B
#       modified:   C
#
# Untracked files:
#       D

Some changes to B are in the index, some aren't. C is not staged at all.

How can I update B in the index (stage its unstaged changes) without adding C?

I.e. I would like for the index to look like this:

# Changes to be committed:
#       modified:   A
#       modified:   B
#
# Changed but not updated:
#       modified:   C
#
# Untracked files:
#       D

In this simple case it can of course be achieved with a simple git add B, but I would like to know if there's a simple answer for the general case. I tried git add --refresh, but if I understand correctly, that only updates stat info.

4

3 回答 3

30

以下命令将更新索引以包含 B 中尚未暂存的其他更改:

git update-index --again
于 2012-04-04T16:56:05.380 回答
1

我不知道这样做的完全微不足道的方法,但是:

git status --porcelain

将文件 B(并且只有 B)显示为状态“MM”,因此:

git status --porcelain | grep ^MM | cut -d' ' -f 2

将生成此类文件的列表。

不过,“重新添加”A 并没有什么坏处。

您也可以使用git diff-index --cached --name-status HEAD. (如果你的 git 太老了,可能需要这个git status --porcelain。)

于 2012-04-04T08:18:18.027 回答
0

而不是--refresh,你应该使用--update

git add --update

在此之后,git status应该看起来像:

# Changes to be committed:
#       modified:   A
#       modified:   B
#       modified:   C
#
# Untracked files:
#       D
于 2021-12-28T22:58:51.753 回答