How to remove a directory from git repository?

1,585,764

Solution 1

Remove directory from git and local

You could checkout 'master' with both directories;

git rm -r one-of-the-directories // This deletes from filesystem
git commit . -m "Remove duplicated directory"
git push origin <your-git-branch> (typically 'master', but not always)

Remove directory from git but NOT local

As mentioned in the comments, what you usually want to do is remove this directory from git but not delete it entirely from the filesystem (local)

In that case use:

git rm -r --cached myFolder

Solution 2

To remove folder/directory only from git repository and not from the local try 3 simple commands.


Steps to remove directory

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root folder (main project directory where the git is initialized) named .gitignore and put that folder name into it. You can ignore as many files/folders as you want

.gitignore file will look like this

/FolderName

remove directory

Solution 3

If, for some reason, what karmakaze said doesn't work, you could try deleting the directory you want using or with your file system browser (ex. In Windows File Explorer). After deleting the directory, issuing the command:
git add -A
and then
git commit -m 'deleting directory'
and then
git push origin master.

Solution 4

You can try this: git rm -rf <directory_name>

It will force delete the directory.

Solution 5

I already had committed the folder before and want to remove the directory in the history as well.

I did the following:

Add folder to .gitignore:

echo Folder_Name/ >> .gitignore

Remove from all commits:

git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch Folder_Name/' --prune-empty --tag-name-filter cat -- --all

remove the refs from the old commits:

git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

Ensure all old refs are fully removed

rm -Rf .git/logs .git/refs/original

Perform a garbage collection

git gc --prune=all --aggressive

push you changes to the online repository:

git push

You are done here.

But you can to the following to push all the changes to all branches with: But be careful with this command!

git push origin --all --force
git push origin --tags --force

After that the folder was removed from git, but was not deleted from local disk.

Share:
1,585,764
Sahat Yalkabov
Author by

Sahat Yalkabov

Updated on July 08, 2022

Comments

  • Sahat Yalkabov
    Sahat Yalkabov almost 2 years

    I have 2 directories on my GitHub repository. I'd like to delete one of them. How could I do that without deleting and re-creating entire repository?