Oh!!! I have added a file that I didn’t want!! What is the next? How can I remove it from my repository?
Don’t worry! You can remove a file from your repository since you are using Git.
If we don’t know when we add that file we can remove it from the beginning using the following command:
1 |
$ git filter-branch --index-filter "git rm --cached --ignore-unmatch {file}" |
If we want to remove it from a concrete commit (usually the last). We should add the commit.
1 2 3 |
$ git filter-branch --index-filter "git rm --cached --ignore-unmatch {file}" {COMMIT} Example: $ git filter-branch --index-filter "git rm --cached --ignore-unmatch {file}" HEAD |
We also can remove it from a range of commits as you can see in the following example:
1 2 3 |
$ git filter-branch --index-filter "git rm --cached --ignore-unmatch {file}" {COMMIT}..{COMMIT} Example: $ git filter-branch --index-filter "git rm --cached --ignore-unmatch {file}" 7b3072c..HEAD |
Ok, I have just finished to remove the file from my repository, what is next?
You should refresh the reflog removing the dereference file and force garbage collect:
1 2 3 |
$ git for-each-ref --format="delete %(refname)" refs/original | git update-ref --stdin $ git reflog expire --expire=now --all $ git gc --prune=now |
Unless you are making a new repository, you should update all branches and tags to remote. And all your team must remove and clone the repository to avoid including again the removed file.
1 2 |
$ git push origin --force --all $ git push origin --force --tags |
I hope this article was useful. We can always add unwanted files when we add files using the command “$ git add .”, for this reason you should avoid it and always add your specific files one by one.