How to Delete file in GIT


how to delete a file in Git using different approaches:

Delete file locally and push changes to remote:

To delete a file locally and push the changes to the remote repository, you can use the following commands:

$ git rm <file_name>
$ git commit -m "Deleted <file_name>"
$ git push

For example, to delete a file called example.txt, you can run:

$ git rm example.txt
$ git commit -m "Deleted example.txt"
$ git push

Remove file from Git repository without deleting locally:

To remove a file from Git repository without deleting it locally, you can use the following command

$ git rm --cached <file_name>

For example, to remove a file called example.txt from the repository but keep it locally, you can run:

$ git rm --cached example.txt

Delete file from specific Git commit:

To delete a file from a specific Git commit, you can use the following command:

$ git filter-branch --tree-filter 'rm -f <file_name>' HEAD

For example, to delete a file called example.txt from the commit abc123, you can run:

$ git filter-branch --tree-filter 'rm -f example.txt' abc123

Note that this command will rewrite the Git history and create a new commit. So, use it with caution.

Delete file from all Git commits:

To delete a file from all Git commits, you can use the following command

$ git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch <file_name>' --prune-empty --tag-name-filter cat -- --all

For example, to delete a file called example.txt from all commits, you can run:

$ git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch example.txt' --prune-empty --tag-name-filter cat -- --all

Note that this command will also rewrite the Git history and create new commits. So, use it with caution.