How to unstage a git file
How to unstage Git files from the index
To unstage a file in the Git version control software, any of the following three commands will suffice, although only the git restore command is recommended:
- git restore –staged file-to-unstage.txt
- git reset file-to-unstage.txt
- git rm –cached file-to-unstage.txt
There may be unintended consequences when you use git reset or git rm. The git restore command is the best option.
Unstage git file example
To unstage a file named file.html that is already added to Git’s index, here is the command:
git restore --staged file.html
Here’s a quick, real-world example of how to unstage a Git file in Git. In this example we do the following:
- Clone a sample Git repo.
- Create a new file with the touch command.
- Add the file to the Git index.
- Unstage the file with git restore.
Devs use the git status command to monitor the state of the file.
$ git clone https://github.com/cameronmcnz/ufe.git Remote repository successfully cloned $ cd ufe Switched to /ufe directory $ touch file.html File named file.html created $ git status Untracked files: file.html $ git add file.html $ git status Changes to be committed: new file: file.html $ git restore --staged file.html Git file unstaged successfully $ git status Untracked files: file.html
Restore and rm to unstage Git index files
The git restore command was introduced in 2019 as part of Git version 2.23.
Prior to the git restore command, people commonly used git reset to unstage Git files, like so:
git reset file-to-unstage.txt
This command still works, but it is not the recommended approach.
The reset command is powerful, and is able to rewrite your branch history. To avoid any unintended consequences with an incorrectly issued instruction, it’s best to avoid reset and stick with restore to untrack a Git file.
Don’t unstage Git files from the index with rm
Another option often cited to remove a file from the Git index is the rm command:
git rm --cached file.txt
However, you should avoid his option, because this may not only remove the file from the index, but remove it from the repo altogether. When others pull after you have pushed, the file may not appear in their repositories at all.
The bottom line? If you want to unstage a file in Git, use the restore command. That’s what it’s there for.