When working in the Git version control system, you may find yourself doing some handling of large numbers of files in a single commit. The commit part is the easy part. Now, we are going to review how to do this with commands such as:
git rm(aka git remove)
Adding Files With git add
Adding files is very simple by using the
git add * command which adds all of the new files that appear as new since the most recent commit.
git status shows a few files to be added. We add them all using a
git add * command, and see that the files are added and ready for a commit:
Removing Files With git rm (git remove)
When you remove a large number of files, you would think that the same process would work for removing from the previous state of the repository. Removing a single file is done with the
git rm filename command. You can use wildcards, but that’s going to do a lot more than you would hope.
WARNING: Seriously, don’t try this on a repository that you care about. If you run a
git rm * just like you did with the
git add * process, you will see that it could be nothing is removed from the local copy of your repo. In worst situations, you may also find that a lot is removed. A new commit will leave you with a rather unfortunate situation.
Git remove is also useful when you need to remove files you have just added to a repository in error.
How to Safely Remove Deleted Local Files From a Git Repo
There is a simple one-liner that will help you safely remove your local deletions from your repository. This is done by using the
git ls-files command with a
--deleted -z parameter. This is piped to a
git rm command using the filename and full path into the
git rm command.
The Magical One-Liner
This is the full one-liner:
git ls-files --deleted -z | xargs -0 git rm
This is the result:
Using that command is much safer. This lets you remove all of the files marked as deleted to ensure your next commit is cleaned of your deleted files and nothing that you unexpectedly removed by a slip of a wildcard statement.
Using git add and git rm (git remove)
To sum things up,
git add and
git rm (git remove) are two of the most useful commands for managing your git repository. They are very simple to use. Another usage of the
git rm (git remove) command is to remove the local files you just deleted from a git repo.
6 thoughts on “Git Remove Multiple Deleted Files”
So you basically are saying to git “give me a list of all deleted files files and apply `git rm` command to all of them”. Cool! Thanks.
Thanks. Came across this now and saved me some time.
thanks, save me lot of time.
consider `git add -u`.
-u stands for update and will also add any changes to files that are under version control, including deletions.
Great tip, thank you!
thanks your Magical One-Liner command helped a lot 🙂 had to cleanup me repo