Why are there two ways to unstage a file in Git?

后端 未结 12 1853
刺人心
刺人心 2020-11-27 23:48

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

EDIT:

D:\         


        
12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 00:37

    Quite simply:

    • git rm --cached makes git stop tracking the file completely (leaving it in the filesystem, unlike plain git rm*)
    • git reset HEAD unstages any modifications made to the file since the last commit (but doesn't revert them in the filesystem, contrary to what the command name might suggest**). The file remains under revision control.

    If the file wasn't in revision control before (i.e. you're unstaging a file that you had just git added for the first time), then the two commands have the same effect, hence the appearance of these being "two ways of doing something".

    * Keep in mind the caveat @DrewT mentions in his answer, regarding git rm --cached of a file that was previously committed to the repository. In the context of this question, of a file just added and not committed yet, there's nothing to worry about.

    ** I was scared for an embarrassingly long time to use the git reset command because of its name -- and still today I often look up the syntax to make sure I don't screw up. (update: I finally took the time to summarize the usage of git reset in a tldr page, so now I have a better mental model of how it works, and a quick reference for when I forget some detail.)

提交回复
热议问题