I have added a file named \"file1.txt\"
to a Git repository. After that, I committed it, added a couple of directories called dir1
and dir2
Another way if you want to delete the file from your local folder using rm command and then push the changes to the remote server.
rm file1.txt
git commit -a -m "Deleting files"
git push origin master
The answer by Greg Hewgill, that was edited by Johannchopin helped me, as I did not care about removing the file from the history completely. In my case, it was a directory, so the only change I did was using:
git rm -r --cached myDirectoryName
instead of "git rm --cached file1.txt" ..followed by:
git commit -m "deleted myDirectoryName from git"
git push origin branch_name
Thanks Greg Hewgill and Johannchopin!
This is the only option that worked for me.
git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch *.sql'
Note: Replace *.sql with your file name or file type. Be very careful because this will go through every commit and rip this file type out.
EDIT: pay attention - after this command you will not be able to push or pull - you will see the reject of 'unrelated history' you can use 'git push --force -u origin master' to push or pull
git rm
will only remove the file on this branch from now on, but it remains in history and git will remember it.
The right way to do it is with git filter-branch
, as others have mentioned here. It will rewrite every commit in the history of the branch to delete that file.
But, even after doing that, git can remember it because there can be references to it in reflog, remotes, tags and such.
If you want to completely obliterate it in one step, I recommend you to use git forget-blob
https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/
It is easy, just do git forget-blob file1.txt
.
This will remove every reference, do git filter-branch
, and finally run the git garbage collector git gc
to completely get rid of this file in your repo.
More generally, git help
will help with at least simple questions like this:
zhasper@berens:/media/Kindle/documents$ git help
usage: git [--version] [--exec-path[=GIT_EXEC_PATH]] [--html-path] [-p|--paginate|--no-pager] [--bare] [--git-dir=GIT_DIR] [--work-tree=GIT_WORK_TREE] [--help] COMMAND [ARGS]
The most commonly used git commands are:
add Add file contents to the index
:
rm Remove files from the working tree and from the index
If you need to remove files from a determined extension (for example, compiled files) you could do the following to remove them all at once:
git remove -f *.pyc