Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Anonymous

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

EDIT:

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

D:codegt2>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:codegt2>git add a

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

D:codegt2>touch b

D:codegt2>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:codegt2>git add b

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

Solution

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> will unstage any staged changes for the given file(s).

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.

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

Answered By: Anonymous

Related Articles

  • Various ways to remove local Git changes
  • In plain English, what does "git reset" do?
  • Difference between git checkout --track origin/branch and…
  • Why call git branch --unset-upstream to fixup?
  • Why do I have to "git push --set-upstream origin "?
  • Checkout another branch when there are uncommitted changes…
  • git lfs push to github failure on Ubuntu 18.04
  • Why does Git say my master branch is "already up to date"…
  • Git: Create a branch from unstaged/uncommitted changes on…
  • How can I reconcile detached HEAD with master/origin?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Reverse a string in Java

Next Post:

Get the data received in a Flask request

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error