To remove a directory from your Git repository, you need to:
- Use git rm to remove the directory from Git or from Git and your filesystem.
- Commit the removal (the deletion is automatically staged, no need to run git add).
- Push the change to the remote.
To remove the directory both from Git and from your local files, run:
$ git rm -r dir-name
To only remove the file from Git but to keep it in your file system, run:
$ git rm -r --cached dir-name
For example, to remove a folder called Images from Git, you’ll run the following commands:
$ git rm -r --cached Images $ git commit -m "Remove Images folder" $ git push origin main
Example 1. Remove Directory from Git and Files
Let’s see a concrete example just to make it easier for you.
Here’s an example project that’s under Git version control.
There’s a folder called Images I want to get rid of from both Git and the file system.
To do this, Iet’s run the git rm -r command and commit the changes.
$ git rm -r Images/ $ git commit -m "Remove images folder" $ git push origin main
After running these, the Images folder no longer exists in Git version control or my file system.
Example 2. Remove Directory from Git Only
As another example, let’s start with a project with an Images folder again:
This time, let’s only remove the folder from Git but let’s keep it in the local file system.
To only remove the folder from Git, you need to use the –cached option when removing.
$ git rm -r --cached Images/ $ git commit -m "Remove Images folder" $ git push origin main
But now, the Images folder still exists on the local file system.
As a result, it shows up in the untracked files section in Git.
This is annoying but it makes sense. The folder is not tracked by Git but is still there in the project folder.
To remove it from the Untracked files section, you need to place the folder into the .gitignore file.
If you already have a .gitignore file, add the Images/ folder there as a line of text.
If you don’t have the .gitignore file, you can create one with your command line.
For example, let’s create a .gitignore file, add Images to it and commit the change.
$ touch .gitignore $ echo "Images/" > .gitignore $ git add .gitignore $ git commit -m "Add gitignore and place Images/ there" $ git push origin main
Now the Images/ folder is no longer tracked by Git and it doesn’t annoy you in the Untracked files section when running git status.
Thanks for reading. Happy coding!
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
- Artificial Intelligence2023.05.16Humata AI Review (2023): Best PDF Analyzer (to Understand Files)
- Python2023.05.139 Tips to Use ChatGPT to Write Code (in 2023)
- Artificial Intelligence2023.04.1114 Best AI Website Builders of 2023 (Free & Paid Solutions)