Git Basics: How to remove files from the working tree and the index?


Earlier we discussed about 'git add' to add files to index, 'git mv' to rename or move files. We have also discussed about 'git commit' to push the changes to staging. Now what to do if one wants to remove a file from working tree and index?

 

We are today going to discuss on this topic. We have a command 'git rm' to handle this case. Let's start today's discussion, part of the 'Git Tutorial Series'.

 

Remove files from the working tree and the index (www.kunal-chowdhury.com)

 

Though you can directly delete a file or files from a working tree and commit the changes using the command 'git add -A' or 'git commit -a', but Git provides an alternative way to delete the file using the 'git rm' command.

 

The 'git rm' command not only removes the specified file from your working tree, but also removes it from the index. There are no options to remove the file only from the working tree and still keep it indexed.

 

The files being removed have to be identical to the tip of the branch and no updates to their contents can be staged in the index. You can override this default behaviour by using the -f option/switch. When the option --cached is given, the staged content has to match either the tip of the branch or the file on the disk, allowing the file to be removed from just the index.

 

Here's the list of command with parameters to use:

 

Remove a file from working tree and index:

$ git rm <filePath>                              # You can also use a global asterisk

 

Remove all files in the directory:

$ git rm <directoryPath>

 

Forcefully remove the file and the index:

$ git rm -f <filePath>

$ git rm --force <filePath>

 

Recursively remove files in folder and subfolders:

$ git rm -r <directoryPath>

 

Force to recursively remove files in folder and subfolders:

$ git rm -r -f <directoryPath>

$ git rm -r --force <directoryPath>

 

 

Was this post useful? If you came to this page by searching online about git basics, please have a look into my other blog posts. Subscribe to the RSS feed or the email newsletter to keep yourself updated.

 

 

 


If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

0 comments

 
© 2008-2016 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top