Remove single file from staging or from commit
Sometimes we accidentally add a file to staging or commit it to git repo. Lets get to how to we can remove it in this tip.
Before going further with tip, lets revisits states in which file might exists,
Untracked - when you first create the file, it goes in this area
Staged/ index - when you use
git add
command on the file, it goes in this areaCommitted - when you use the
git commit
on the file, it goes in this areaModified- the file is committed but has the local changes which are not committed or staged yet.
Remove from staging area
To remove from staging, we can use following command-
git rm --cached <file_name>
Here, we are using the rm
command along with switch --cached
which indicates the file to be removed from the staging or cached area.
For example, we can use following command-
git rm --cached unwanted_file.txt
Remove single file from committed area
Note: In this, it is assumed, you doing it on local latest commit and not the commit which is pushed to remote repository.
Removing file from committed area requires 3 commands to be run, they are as follows-
git reset --soft HEAD^1
Above will undo the latest commit. if you do git status
you will see files in the staging area. Now, we can easily remove it from staging area, as mentioned from previous point.
git rm --cached <file-name>
By running above command, the file will appear in the untracked file section.
Now, we removed the single file, lets commit back those remaining files-
git commit -m "<your-message>"
Written by Abhijeet Sutar
Related protips
2 Responses
Hey when you want to remove a file from the staging area you can do git reset HEAD -- <file>
The way you have suggested is very wrong I feel and should be updated soon.
Please let me know if I am wrong.
Oh, this is cool information, I suffer from the fact that I accidentally add the wrong thing. thank you very much.