Skip to main content

How to Remove Files from Git Repositories Without Breaking Your Project

Learn how to remove files in Git repository, avoid common mistakes, and manage your repository cleanly even in complex or sensitive scenarios.
Sep 1, 2025  · 15 min read

Removing files in Git isn’t always as simple as it seems. You delete a file from your system, but it doesn’t mean it’s gone from the repository. It may still exist in your history, or worse, get committed by accident, like a config file or an API key.

In this guide, you’ll learn how to remove files from Git. We’ll start with basic commands like git rm, then go into more advanced methods like cleaning untracked files and editing your commit history.

Prerequisites

Before we remove files with Git, let’s make sure everything is set up.

First, check if Git is installed. Open your terminal and run:

git --version

If you see a version number, you’re good to go. 

Installing git

If you see a version number, you’re good to go.

You can also install a Git GUI like GitHub Desktop, Sourcetree, or GitKraken if you prefer a visual interface. But in this guide, I’ll use the command line (Git Bash).

Make sure you have permission to make changes in the repository, especially if you’re part of a team or working with a remote repo like GitHub or GitLab.

Note: Some file removal actions can't be undone. So, it’s a good idea to back up your project or at least double-check the state of your repo before running any commands that delete files.

Once that’s done, let’s get started.

Basic File Removal in Git

There are a few different ways to remove files in Git, depending on what you want to do. Let’s see some common options:

Using git rm

The git rm command removes files from your Git repository. When you run it, two things happen:

  • Git removes the file from your working directory
  • It stages that change for the next commit

But Git doesn’t only delete the file. It tracks the deletion in your history. Once you commit, the file is officially removed from the project.

git rm file1.txt

deleting a file using the git rm command.

You can remove one file, many files, or a group of files using wildcards. 

For example, to remove all log files:

git rm *.log

This tells Git to remove every file in the folder that ends in .log. You can confirm the change using:

git status

Deleting multiple files with one git rm command.

Delete multiple files with one git rm command. Image by Author.

Want to remove all files inside a folder but not the folder itself? Use:

git rm temp/*

This deletes every file inside the temp folder without deleting the folder itself.

Deleting files inside a folder using git rm command.

Git also adds some safety checks. If a file has changes that aren’t committed yet, Git won’t delete it unless you force it. So use this only if you’re sure those changes can be discarded:

git rm -f

Removing uncommitted file using the -f option.

To remove a full folder and everything in it, add the -r flag:

git rm -r testfolder

This removes testfolder and all files inside it.

Removing the entire folder and its content using the git rm -r command.

Now, to commit the change, run the following command:

git commit -m "removed log files”

Commit the deletion with git commit command.

Key git rm options

Here are the most common options you’ll use with git rm:

1. <filename>

This is the basic usage. Just list the files you want to remove:

git rm file1.txt file2.txt

You can also use a wildcard to remove multiple files of the same type. For example, to remove all .txt files:

git rm *.txt

(Here, * means all. It matches any filename that ends in .txt.)

2. --cached

This removes the file from the repository but keeps it on your computer. Let’s say I accidentally added a sensitive file like config.env. I don’t want it in the repo, but I still need it on my machine. So I’d run:

git rm --cached config.env

Here, git rm will delete it from the repository and working directory. And --cached untracks it from Git (so it won't be pushed), but leaves it physically in place.

To prevent it from being added again, add it to .gitignore:

echo config.env >> .gitignore

Stop tracking the file using the --cached option in git rm.

3. -r

It stands for recursive. Instead of one file, this recursively deletes the directory and its contents. Without this, Git will give you an error if you try to remove a folder.

git rm -r <folder-name>

Here, I created a folder named testfolder and two files inside it: a.txt and b.txt. Next, I run the following command:

git rm -r testfolder

This removed the folder along with all the contents and files inside it

Remove the entire folder using the -r option.

4. --dry-run

If you’re not sure what will happen if you remove a file, use git rm with --dry-run option like this:

git rm --dry-run <filename>

This is a safe way to preview what will be removed. 

Preview the files before removing with the --dry-run option.

Or if you’re cleaning up untracked files and want to double-check what’ll be removed, use:

git clean -n

This will only show what this command will delete.

Preview the untracked file before deleting with git clean -n command.

Comparative Workflow Analysis

There’s more than one way to remove a file in Git. The methods might seem the same, but they don’t behave the same.

git rm vs manual deletion

Let’s take a file called file.txt. Say I don’t need it anymore.

One way to remove it is to delete it directly from the system.

On Linux, macOS, or Git Bash:

rm file.txt

On Windows (command prompt): 

del file.txt

Remove the file with rm command and check the status with git status command.

This deletes the file from your folder. But Git doesn’t know that yet. So you have to manually tell Git that the file was removed:

git add file.txt

This stages the deletion so it’s included in the next commit.

Stage the deletion with the git add command.

If you deleted several files and don’t remember all of them, you can run:

git add -u

This stages all tracked files that were changed or deleted. It won’t include untracked files.

Now you commit the change:

git commit -m "Remove file.txt"

If you use git rm, it handles everything in one step. It deletes the file and stages the change right away:

git rm file.txtgit commit -m "Remove file.txt"

No need to run git add separately. It’s cleaner and you won’t forget to stage the deletion.

The git rm command deletes and stages the file in one go.

In short:

  • Manual deletion requires extra steps to make sure Git picks up the change.
  • If you forget to stage the deletion, Git still thinks the file exists, which can cause confusion in commits or merges.
  • git rm is cleaner and safer when you're intentionally removing tracked files.

Restore deleted files in Git

What if you delete a file and later realize you still need it? No problem. Git gives you a few ways to bring it back depending on when you notice the mistake.

If you haven’t committed yet:

Let’s say you deleted the file but haven’t committed the change. You can restore it from the last commit like this: 

git restore file.txt

This brings the file back into your working directory from the latest commit.

If you already committed the deletion:

That’s fine too. First, find the last commit where the file still existed:

git log -- file.txt

Look through the log and copy the commit hash where the file was still there. Then run:

git checkout <commit hash> -- file.txt

In older versions of Git, you could use the above command. This command restores a file from a specific commit, but could also switch branches.

Starting from Git 2.23, this was split into two clearer commands:

  • git switch (for switching branches)
  • git restore (for restoring files)

If you only want to restore a file from a commit, use:

git restore --source=<commit-hash> --file.txt

This pulls the file from that commit and puts it back in your working directory.

If you’re not sure when the file was deleted:

Maybe you’ve made a bunch of changes and don’t remember when the file went missing. In that case, use git reflog or reference log

git reflog

This shows a complete history of your Git commits, checkouts, resets, and everything.

But git reflog is local only and won’t work on remotes. If you’re working with a remote repo, it’s better to use git log -- file.txt to track the history of that file.

Once you find the point where the file still existed, restore it using either git checkout or git restore like before.

Fix Missing Files in Git

Sometimes files get deleted directly from the system—maybe through a file explorer, a terminal rm command, or even by accident. When this happens, Git doesn’t automatically clean things up. Instead, it marks those files as missing and waits for you to handle the removal properly.

Let’s see how you should deal with such a situation, step by step.

Step 1: Check for missing files

Run this in your project folder:

git status

Check the file with the git status command.

If Git says a file is deleted, that means it’s gone from your system, but the change hasn’t been staged yet.

Step 2: Stage the deletion 

To tell Git to stage all changes (including deleted files), run:

git add -A
  • git add -A = stage all changes (new, modified, deleted).
  • git add -u = stage modified + deleted, but not new files.

This stages all file changes: new, modified, and deleted. Then commit the update:

git commit -m "Removed missing files"

Stage everything with the git add -A command.

This is the safest way to clean up because it catches every change in one go.

Step 3: Push to the remote 

If you’re working with a remote repository, push the commit:

git push origin <branch-name>

Replace <branch-name> with the working branch, like main or dev.

Step 4: Alternatively

Let’s say you’ve deleted a bunch of files manually, maybe by accident, or while cleaning up. Git still thinks those files exist until you tell it otherwise.

If you don’t want to remove each one with git rm, there’s a faster way to clean things up.

Run this command in your terminal:

git ls-files --deleted -z | xargs -0 git rm

Here’s what it does:

  • git ls-files --deleted lists all files that Git is tracking but that are now missing.
  • xargs -0 git rm passes those file names to git rm and removes them from Git’s index.

This is quite helpful when you’re working on a big project and want to clean things up quickly.

Automatically remove all missing files.

Note: I got this message because there are no tracked files that are currently missing from your disk.

Advanced File Removal in Git

Now that we've covered the basics, let’s look at more advanced situations where removing a file from Git isn't as simple as running git rm. These are cases where either sensitive data is involved or untracked files need to be cleaned up carefully.

Remove sensitive data from Git

Sometimes a file with private data, such as API keys or passwords, is accidentally committed. Deleting it normally won’t help. Because Git keeps a complete history, and the file still exists in earlier commits.

To erase it completely, you can use the git filter-repo command: git filter-repo (recommended)

This is a newer and better alternative to filter-branch. It’s faster, safer, and easier to use.

First, install it (you’ll need Python and pip):

pip install git-filter-repo

Then run:

git filter-repo --path hide.txt --invert-paths

This removes the hide.txt file from every commit in your repo’s history.

To confirm, run:

git log --all -- supersecrets.txt

If the file is gone, add it to .gitignore so it doesn’t get tracked again:

echo hide.txt >> .gitignore

If you're working with a team, clean the rewrite history and force-push the changes:

git push origin --force --all

Then let your teammates know. They’ll need to re-clone or reset their local copies to avoid errors.

Clean untracked files with git clean

Let’s break it down:

  • Tracked files are in Git’s history. To remove them, use git rm, then commit.
  • Untracked files are not in Git at all. These can build up and clutter your project.

To delete untracked files or folders, use git clean.

Here are the most useful options:

git clean -n     # Show which untracked files will be removedgit clean -nd    # Show which untracked folders will be removedgit clean -fd    # Delete all untracked files and folders. It is destructive.

Use the git clean command to delete and untrack the files

Here:

  • -n means preview only.
  • -f means force delete.
  • -d includes folders in the cleanup.

Note: git clean won’t touch tracked files. But it will delete anything untracked, even files you meant to keep. So, always use -n first to see what it will remove.

File Removal in GitHub & GUI Tools

Most of what we’ve covered so far uses the command line. But not everyone works that way and that’s totally fine. Some developers use visual tools when working directly in GitHub.

So let’s see how deleting files works in GitHub’s web interface and other GUI tools, and how that compares to the command line.

Delete files in GitHub website

If you're working in GitHub’s browser interface, you can delete files without using the terminal.

Here’s how it works in the 2025 interface:

  1. Open the file you want to delete.
  2. Click the three dots in the top-right corner.
  3. Choose the Delete file from the dropdown.

Deleting the file in the GitHub web interface

GitHub will then show a commit message box. Add a short message like:

Delete practice.py

You can also write an optional description.

Next, choose how to save the change:

  • Commit directly to the main branch
  • Or create a new branch and start a pull request (recommended for team workflows)

Click Commit changes, and GitHub will remove the file and save the deletion as a commit, just like git rm does from the command line.

Delete files with Git GUI tools

If you use a Git GUI like GitHub Desktop, Sourcetree, or Tower, the process is also simple:

  1. Delete the file in your file explorer or within the app.
  2. The app shows the deletion under “Changes” or “File Status.”
  3. Review, stage, and commit the change.

Each tool looks a bit different, but the workflow is similar: You track changes visually, and commit when you’re ready.

Best practices by platform

Here’s a quick look at how file deletion works across different platforms, and when each one is most useful:

  • GitHub (Web): Good for quick fixes and small updates. Avoid it for big cleanups or sensitive files. 
  • Git GUI tools: Great for daily work. Easy to see changes and commit safely. 
  • Command line: Most flexible and helpful. Best for advanced tasks like buld edits or history changes. 

Best Practices for Git File Removal

Removing files in Git might look simple, but one wrong step can break your code. Here are some practical tips I use to make sure deletions are safe and controlled, especially on shared or long-term projects.

Always verify before deleting

Before removing a file, take a minute to confirm what it’s doing:

  • Run git status to see if it’s staged or modified.
  • Use git log -- <filename> to check its commit history.

This quick check saves me hours of recovery work later.

Use atomic commits

An atomic commit means one commit per logical change.

For example, if I’m deleting unused files, I commit only those deletions, separate from code edits.

Here’s why it’s quite helpful:

  • Debugging is easier. Tools like git bisect work better when commits are small and focused.
  • The commit history stays clean and clear.
  • Code reviews go faster.

Collaborate carefully on history rewrites

Rewriting history with tools like git filter-repo affects everyone on your team. To avoid chaos:

  • Communicate before rewriting shared branches.
  • Use git push --force carefully as it rewrites remote history.
  • Tell teammates to re-clone or reset their local repos afterward.

Use --dry-run before running destructive commands

Before running a command that deletes files, always test it:

git clean -n

This shows what would be deleted without deleting anything. Here’s why I think you should always do this: 

  • It stops you from removing files you actually want to keep.
  • It’s a safety net, especially in large projects where a single mistake could wipe out logs or generated files.

Combine git rm --cached with .gitignore

If you accidentally commit something that shouldn’t be in the repo (like a config file or logs), fix it in two steps:

  1. Untrack the file:```git rm --cached <filename>
git rm --cached <filename>

This tells Git to stop tracking the file but leaves it on your computer.

  1. Add it to .gitignore:
echo <filename> >> .gitignore

Here’s why it’s helpful:

  • Keeps sensitive or local files (like .env, .log, or node_modules) out of the repo.
  • Prevents clutter in your Git history.
  • Future edits to those files won’t trigger changes in Git.

Git Edge Cases: Staging & Empty Folders

Sometimes file removal doesn’t go as expected. You may stage the wrong file or run into issues with empty folders. 

Here’s how I handle common edge cases.

Unstage a file without removing your changes

Let’s say I run git add . and accidentally stage a file I didn’t mean to. I don’t want to lose my changes—I just want to unstage it.

To fix that, I run:

git reset HEAD <filename>

This unstages the file but keeps the edits in place.

To confirm, I use:

git status

Now the file should show as "modified" instead of "staged."

Keeping empty folders in the repo

By default, Git ignores empty folders. If I try to commit a folder with no files inside, Git skips it.

But sometimes I want to keep that folder in the repo either for future logs or uploads. The usual fix is to add a placeholder file called .gitkeep.

Here’s how:

touch logs/.gitkeepgit add logs/.gitkeepgit commit -m "Keep logs folder in the repo"

This makes the folder "non-empty," so Git tracks it.

Note: .gitkeep isn’t built into Git. It’s just a convention. You can name the file anything, but .gitkeep tells others what it’s for.

Git File Removal Troubleshooting

Here are a few common problems I’ve run into when removing files in Git and how to fix them.

The file still appears in the remote repository

You deleted the file, committed the change, but it’s still on the remote repo. Maybe you forgot to push.

So make sure to run:

git push origin <branch-name>

Also check:

  • Are you on the correct branch?
  • Did your commit actually include the file deletion?

Problems with submodules

Submodules are Git repositories inside other Git repositories. They don’t behave like normal folders.

If you're deleting files inside a submodule:

  • Go into the submodule folder
  • Commit and push the changes from within that submodule

If you're removing the submodule entirely:

  • Delete the submodule folder
  • Remove any references in .gitmodules and .git/config

Detached HEAD state

In Git, HEAD usually points to the current branch. But sometimes it points to a specific commit instead, that’s called a detached HEAD.

This happens if you:

  • Check out a commit by its hash
  • Switch to a tag
  • Check out a remote branch without setting it to track

Check your status:

git status

If you see:

HEAD detached at <commit-hash>

You’re not on a branch, and any new changes may be lost when you switch away.

HEAD Detached in removing the file in git

Here’s how you can fix it: 

If you’ve made changes and want to keep them, run this:

git checkout -b <new-branch-name>

This puts your work on a new branch and saves it.

HEAD Reattached in git

If you’ve already committed the changes and want to move them to another branch later, do this:

git checkout -b temp-branch          # from detached HEADgit checkout main                    # or another target branchgit merge temp-branch

If you didn’t make any changes and just want to get out of detached HEAD, run this:

git checkout <branch-name> 

That’s it. Your HEAD is now reattached, and everything is back to normal.

Permission or state errors

Sometimes Git won’t delete a file usually on Windows. This can happen if:

  • The file is open in another program
  • Git doesn’t have permission to update it

Here’s how to fix this:

  • Close any apps using the file
  • Restart your terminal as Administrator (on Windows)

Merge or rebase issues

If you see errors like:

  • you are not currently on a branch
  • merge conflict

You’re likely in the middle of a merge or rebase.

To finish a rebase after resolving conflicts:

git rebase --continue

To cancel the rebase or merge entirely:

git reset --merge

This restores your repo to how it was before the merge started.

Want to throw away all local changes and reset your working directory? 

Try this:

git restore .

This puts all files back to their last committed state.

Final Thoughts 

When you’re removing files in Git, it’s easy to mess up if you’re not paying attention. One small mistake can lead to bigger problems: broken code, lost work, or confusion in your team. That’s why, take a second to double-check what you’re doing.

Use the right command for the situation. If you’re not sure what something will do, test it with a dry run first. And if you’re working with others, make sure everyone’s on the same page.

There’s a lot more Git can do beyond deleting files. You can delete branchesundo mistakes using reset and revert, or see exactly what changed with git diff. The more you learn, the smoother your workflow gets.

Take it one step at a time. That’s how you get good at this stuff.

Git Remove File FAQs

What does “staging the removal” mean?

Staging means getting changes ready for your next commit. When you run git rm filename, Git deletes the file from your folder and prepares that deletion to be saved in the next commit. This is called staging the removal. The change isn’t permanent until you run git commit.

What’s the difference between git rm and rm?

rm deletes a file from your local folder only. Git won’t track this change until you specify it. 

git rm removes the file and stages the deletion for your next commit, so Git deletes it from the repo too.

When should I use git push origin vs git push?

Here’s when to use each:

  • Use git push if your branch is already connected to a remote. 
  • Use git push origin when you want to be clear about which remote to push to, like when you're pushing a new branch or have more than one remote.

What does git pull do?

git pull updates your local branch with the latest changes from the remote. It fetches new commits from the remote and then merges them into your current branch.


Laiba Siddiqui's photo
Author
Laiba Siddiqui
LinkedIn
Twitter

I'm a content strategist who loves simplifying complex topics. I’ve helped companies like Splunk, Hackernoon, and Tiiny Host create engaging and informative content for their audiences.

Topics

Top DataCamp Courses

Track

Git Fundamentals

0 min
Learn version control with Git from basics to advanced workflows. Track changes, manage repositories, and collaborate efficiently.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Tutorial

Git Clean: Remove Untracked Files and Keep Repos Tidy

Master git clean to safely remove untracked files and directories. Learn key options, interactive mode, and best practices to prevent data loss.
Allan Ouko's photo

Allan Ouko

Tutorial

Git Delete Branch: How to Remove Local and Remote Branches

This guide explains how to delete branches in Git—locally and remotely—while following best practices to avoid accidental data loss.
Ashlyn Brooks's photo

Ashlyn Brooks

Tutorial

Git Prune: What Is Git Pruning and How to Use Git Prune

Git prune is a Git command that removes objects from the repository that are no longer reachable from any commit or branch, helping to free up disk space.
François Aubry's photo

François Aubry

Tutorial

Git Remote: A Complete Guide with Examples

Learn about Git remotes, their purpose, and how to use them for version control in your project. Includes practical examples.
Mark Pedigo's photo

Mark Pedigo

Tutorial

How to Use .gitignore: A Practical Introduction with Examples

Learn how to use .gitignore to keep your Git repository clean. This tutorial covers the basics, common use cases, and practical examples to help you get started!
Kurtis Pykes 's photo

Kurtis Pykes

Tutorial

Git Status: How To Track Changes in Your Project with Confidence

Learn how to use the git status command to monitor your repository’s state. This guide is perfect for beginners and early‑career practitioners who want an optimized Git workflow.
Khalid Abdelaty's photo

Khalid Abdelaty

See MoreSee More