Git でファイルをステージ解除する方法が 2 つあるのはなぜですか? 質問する

Git でファイルをステージ解除する方法が 2 つあるのはなぜですか? 質問する

git は、git rm --cachedファイルをステージ解除することを提案する場合と、 を提案する場合がありますgit reset HEAD file。どちらをいつ使用すればよいのでしょうか?

D:\code\gt2>git init
Initialized empty Git repository in D:/code/gt2/.git/
D:\code\gt2>touch a

D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       a
nothing added to commit but untracked files present (use "git add" to track)

D:\code\gt2>git add a

D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#       new file:   a
#
D:\code\gt2>git commit -m a
[master (root-commit) c271e05] a
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 a

D:\code\gt2>touch b

D:\code\gt2>git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       b
nothing added to commit but untracked files present (use "git add" to track)

D:\code\gt2>git add b

D:\code\gt2>git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   b
#

ベストアンサー1

git rm --cached <filePath> ファイルのステージングを解除するのではなく、リポジトリからファイルの削除をステージングします(以前にコミット済みであると想定)。ただし、ファイルは作業ツリーに残ります (追跡されていないファイルが残ります)。

git reset -- <filePath>指定されたファイルに対してステージングされた変更をすべてステージング解除します。

つまり、git rm --cachedステージングされた新しいファイルで を使用した場合、そのファイルはこれまでコミットされたことがないので、基本的にはステージング解除したように見えます。

git 2.24にアップデートこの新しいバージョンのgitでは、 の代わりに
を使用できますgit restore --stagedgit resetgit ドキュメント

おすすめ記事