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:

  1. 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) or del 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
    
  2. Stage the Deletion: Stage the deletion of the file for the next commit using the git add command.

     
    git add example.txt
    
  3. Commit the Deletion: Commit the deletion of the file to the repository.

     
    git commit -m "Delete example.txt"
    
  4. 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
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github