20

I deleted a bunch of files and directories from a Git repository using rm, the Finder, etc.

I'm looking for a Git command that'll record these to the index as marked for removal, as if I had called git rm on them.

I understand git add -u will do this, along with a bunch of other things. I'd like my command to exclusively handle removals.

kch
  • 77,385
  • 46
  • 136
  • 148
  • Related, but not an exact duplicate: [Removing multiple files from a Git repo that have already been deleted from disk](http://stackoverflow.com/q/492558/456814). The other question already states that `git rm` can stage the removed files, it's just looking for a way to stage them all with a single invocation of `git rm`. –  Aug 05 '14 at 15:19
  • Possible duplicate of [Removing multiple files from a Git repo that have already been deleted from disk](https://stackoverflow.com/questions/492558/removing-multiple-files-from-a-git-repo-that-have-already-been-deleted-from-disk) – Adam Michalik Jul 30 '18 at 08:19

5 Answers5

35

Without spaces in filenames:

$ git rm `git ls-files -d`

More robust:

$ git ls-files -z -d | xargs -0 --no-run-if-empty git rm
Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
8

Take a look what Jonio C Hamano wrote in "Re: [PATCH 1/2] Documentation: 'git add -A' can remove files" post at git mailing list, namely that this question looks like XY problem (you are asking about assumed solution Y to the problem, instead about the problem X itself). The solution to problem (if it is really "XY problem" situation) might be:

  • git commit -a, which would automatically pick up deletions, committing current state of tracked files in working directory

  • git add -A, which would add not ignored untracked files and remove no longer existing files, e.g. if you want to create commit from sideways update of working directory, e.g. unpacking a snapshot or result of rsync.

Nevertheless if what you ask is a problem (and not solution), then as you can see from other answers there are tools in place to do it.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jakub Narębski
  • 309,089
  • 65
  • 217
  • 230
4

Charles Bailey's answer nudged me towards this, but I still welcome something shorter.

$ git diff --name-only --diff-filter=D | xargs git rm
kch
  • 77,385
  • 46
  • 136
  • 148
2

In Git 2.0, git add behaves like git add --ignore-removal <pathspec> which ignores paths you removed from your working tree.

You can use git add --all <pathspec> to record the removals.

Run git status to check the paths you removed from your working tree.

Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
0

This command will give you a list of all deleted files which will be forward to git rm. So all files will be removed. If no deleted files were found, nothing will be happen:

git ls-files -z -d | xargs -0 --no-run-if-empty git rm

Roman
  • 2,530
  • 2
  • 27
  • 50