How to Delete a File from a Git Repository
- Steps to deleting a file from repository
- The git rm Command
- The git push Command
Sometimes you need to delete a particular file from a git repository for some reason. In case you have accidentally committed a sensitive file to your git repository and now want to delete it, follow the guidelines below.
Steps to deleting a file from repository¶
Note that since Git is a version control system, it will allow you to recover the deleted files anytime you need it. Here are the 2 steps to follow:
1. Removing a file
We will recommend you to use the git rm command for removing a file both from the git repository and the file system. Consequently, you need to run the following command:
git rm file1.txt git commit -m "remove file1.txt"
If you wish to delete the particular file only from the git repository and leave it in the file system, run:
git rm --cached file1.txt git commit -m "remove file1.txt"
2. Pushing changes
Finally, you need to push the changes to your remote repository using the git push command like this:
git push origin branch_name
The git rm Command¶
Whenever it is necessary to delete a particular file or a group of files from a git repository, you can use the git rm command. Additionally, you can use this command to remove files from the staging index and the working directory.
Consider that this command gives no option for removing a file only from the working directory. In case an inconsistency occurs between the HEAD version of a file and the staging index or the working tree version, the removal will be blocked by Git.
The git push Command¶
This command is used for uploading the content of the local repository to the remote. It can be considered as the opposite of the git fetch command. The latter is targeted at importing files to the local branches.
The git push belongs to the commands that are included in the “syncing” process. Such commands work on remote branches that are organized by the git remote command. You can upload commits by running git push and download by invoking git fetch and git pull.