How to Remove Directory in Git

Azhar Bashir Khan Feb 02, 2024
How to Remove Directory in Git

This tutorial will introduce how to remove directories or folders in Git.

We have many directories or folders to group different files in a typical development environment.

We may sometimes need to delete some irrelevant directories.

We will now illustrate this with an example.

Using git rm to Remove Directories in Git

Suppose we have a specific directory and no longer wish to keep it in the repository in Git.

We can remove the directory or folder in our repository using the git rm command with the -r option.

The syntax of the command is git rm -r <directory_name>.

It causes the removal of the directory and its contents from the repository recursively.

Suppose we have a directory named misc, which we want to remove from the repository.

$ ls misc
tmp1.txt

We can remove the directory misc and its contents as follows.

$ git rm -r misc
rm 'misc/tmp1.txt'

Thus, we have now removed the directory misc from the Git repository.

We now need to commit and push this removal of the directory to the remote repository.

We will now do as follows.

$ git commit -m "removed misc directory"
[main b89f021] removed misc directory
 1 file changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 misc/tmp1.txt
 
$ git push origin main

Thus, now when other team members pull the changes from the remote repository, the directory misc will be removed.

Sometimes, we may wish to keep the directory in the local filesystem but remove it from tracking in the remote repository.

For this, we can use the --cached option along with the git rm command as follows.

$ git rm -r --cached misc

Please note this will still remove the misc directory from the filesystem of the other team members’ machines when they pull the changes from the remote repository.

It only keeps the directory misc in the filesystem of our local machine, where we have executed the above command.

Related Article - Git Directory