How Do I Delete a File from a Git Repository?
Better Stack Team
Updated on June 24, 2024
To delete a file from a Git repository, you need to perform the following steps:
Delete the File Locally: Delete the file from your local working directory using your operating system's file management tools or by running the
rm
command (on Unix-like systems) ordel
command (on Windows).For example, to delete a file named
example.txt
, you would run:rm example.txt # On Unix-like systems del example.txt # On Windows
Stage the Deletion: Stage the deletion of the file for the next commit using the
git add
command.git add example.txt
Commit the Deletion: Commit the deletion of the file to the repository.
git commit -m "Delete example.txt"
Push Changes (if necessary): If you're working with a remote repository and you want to push the changes to it, you can use the
git push
command.git push origin <branch-name>
Replace
<branch-name>
with the name of the branch you're working on.
Note:
- Deleting a file from a Git repository involves both removing the file from the working directory and staging the deletion in Git.
- After committing the deletion, the file will be removed from the repository's history starting from that commit.
- Deleting a file locally doesn't automatically delete it from the remote repository. You need to push the deletion commit to the remote repository if you want to remove it from there as well.
Got an article suggestion?
Let us know