dallonsi
dallonsi

Reputation: 1526

git: equivalent of "git add -u" with "git rm"

Is there a way to remove all files from the index that are deleted ?

I usually use git add . -u to add all files to my staging zone that are tracked and modified. How would I do a command like git rm . -u ?

Upvotes: 0

Views: 106

Answers (2)

jthill
jthill

Reputation: 60275

When you want to get brutal, the core commands are always an acceptable option:

git diff-files --diff-filter=D --name-only \ 
| git update-index --remove --stdin

Upvotes: 1

torek
torek

Reputation: 488183

In modern Git, git add -u . already removes from the index any file that you have removed from your working tree:

$ mkdir t1 && cd t1 && git init
Initialized empty Git repository in ...
$ echo example > readme
$ echo somefile > somefile
$ git add .
$ git commit -m initial
[master (root-commit) 95caaab] initial
 2 files changed, 2 insertions(+)
 create mode 100644 readme
 create mode 100644 somefile
$ ls
readme          somefile
$ rm somefile
$ git add -u .
$ git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        deleted:    somefile

If you have an ancient Git, git add -u might not stage these removals—I can't recall the behavior of Git 1.7 here. If so, consider using the --all flag. You could also use git status -s to detect missing work-tree files, which will have SPACED as their two letter status:

$ git restore --staged somefile
$ git status -s
 D somefile

so that git status -s | grep '^ D' produces the list of such files. Others like to use cut and so on to generate a removal command, but I prefer to do:

git status -s >/tmp/x
vim /tmp/x

and then, in the editor, use commands to delete all the non-space-D files, then turn the remaining lines into git rm commands:

:v/^ D/d
:%s/^ D/git rm/

for instance. If some file names have white space, the second vim command would be:

:%s/^ D \(.*\)/git rm "\1"/

Some eyeball inspection will verify that this is indeed what I want to do, after which ZZ or :x exits vim with a file in /tmp/x that I can run using sh /tmp/x. Voila, mission accomplished.

Upvotes: 3

Related Questions