How to Delete a File or a Directory from a Git Repository
Sometimes you need to delete a particular file or a directory from a git repository. 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
Removing files or directories
To remove a file both from the git repository and the file system, run the git rm command as follows:
git rm file1.txt
git rm --cached file1.txt
In case you want to delete multiple files at once, you should list all the file names as it is shown below:
git rm file1.txt file2.txt
You can specify the file name by putting asterisk as a wildcard. It will delete all the files that match the pattern.
git rm file*
To delete a folder, run the git rm command in a recursive (-r) mode:
git rm -r folder-name
Committing the changes
The next step is committing the changes by running the git commit command:
git commit -m "remove file1.txt"
Finally, you need to push the changes to your remote repository using the git push command like this (suppose, the name of remote is origin, which is by default) :
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.