为什么有两种在Git中取消暂存文件的方法? [英] Why are there two ways to unstage a file in Git?

查看:256
本文介绍了为什么有两种在Git中取消暂存文件的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时git建议git rm --cached取消暂存文件,有时是git reset HEAD file.我什么时候应该使用哪个?

Sometimes git suggests git rm --cached to unstage a file, sometimes git reset HEAD file. When should I use which?

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
#

推荐答案

git rm --cached <filePath> 不会取消暂存文件,它实际上会暂存文件的删除 从存储库中(假设它以前已经提交过),但是将该文件留在了工作树中(留下了未跟踪的文件).

git rm --cached <filePath> does not unstage a file, it actually stages the removal of the file(s) from the repo (assuming it was already committed before) but leaves the file in your working tree (leaving you with an untracked file).

git reset -- <filePath>取消暂存给定文件的所有暂存更改.

git reset -- <filePath> will unstage any staged changes for the given file(s).

也就是说,如果您在已暂存的新文件上使用git rm --cached,则基本上看起来像是您刚刚暂存了该文件,因为它从未提交过.

That said, if you used git rm --cached on a new file that is staged, it would basically look like you had just unstaged it since it had never been committed before.

更新git 2.24
在此较新版本的git中,您可以使用git restore --staged代替git reset. 参见 git文档.

Update git 2.24
In this newer version of git you can use git restore --staged instead of git reset. See git docs.

这篇关于为什么有两种在Git中取消暂存文件的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆