It is essential for commit message to line up with changes. What if you accidentally staged a file that was not intended for current commit?
git rm --cached <FILE-NAME>
Specifying a file name when you use the command provided above will unstage a single file (or more, depending on how many files you have specified).
If you want to get more in depth, continue reading.
Git rm command
git rm is used to remove files from the working tree and also from the index.
This command comes with a handy flag
--cached. Upon using this flag along with specifying name of one or more files, they are removed from index.
This means that the working tree files will not be touched. Only that they will be removed from the staging area that Git uses.
Let’s look at an example
$ git status On branch master No commits yet Changes to be committed: (use "git rm --cached <file>..." to unstage) new file: README.md $ git rm --cached README.md rm 'README.md' $ git status On branch master No commits yet Untracked files: (use "git add <file>..." to include in what will be committed) README.md
I added a file ‘README.md’ to the staging area, and a while later realized that it was a mistake. So, to remove ‘README.md’ from staging area, I used the
git rm command and unstaged it.
After removing it from the staging area, I run
git status and I see that ‘README.md’ is not being tracked, and also that it was not deleted (which would be very disastrous).
git rm along with
--cached flag is the exact opposite of
git add command and can be used safely.
Git reset command
git reset will reset the current HEAD to the state that user specifies.
The command alone is not useful in this context, but we can use the double hyphen
-- option will not interpret arguments as options anymore. And lastly, specify the name of file to remove from staging area.
Let’s look at an example to understand this better…
$ git status On branch master No commits yet Changes to be committed: (use "git rm --cached <file>..." to unstage) new file: README.md $ git reset -- README.md $ git status On branch master No commits yet Untracked files: (use "git add <file>..." to include in what will be committed) README.md
As you can see, the file ‘README.md’, which was previously in staging area, is now unstaged.
There are mainly two commands used to unstage a file in a local Git repository. They are
git rm and
git reset, both are used with special flags to perform the action of unstaging files.