tags:

views:

125

answers:

3

I have a git alias (git undo) that undoes everything in the working directory, including new files, changed files, and deleted files:

!git reset --hard && git ls-files -d | xargs -0 git rm --ignore-unmatch && git clean -fq

On OS X, this works great. On Linux, however, I run into the following issue: if no files have been deleted from the repository, the git ls-files -d | xargs -0 git rm --ignore-unmatch command will fail (xargs will be passed nothing).

Is there a way to have xargs silently move on if it receives nothing from git ls-files?

+2  A: 

From the man page:

--no-run-if-empty, -r
If the standard input does not contain any nonblanks, do not run
the command. Normally, the command is run once even if there is
no input. This option is a GNU extension.

Make sure your version of xargs has that option (man xargs)

rjh
That looks like the answer - strange that the OS X version of xargs doesn't have this option (or uses it by default). Guess I'll have to make some OS-specific aliases. ;)
ABach
OS X is FreeBSD based, and so has the FreeBSD version of xargs. It's POSIX compliant, but does not have GNU extensions.
rjh
A: 

Maybe you want to use xargs' "-r" option:

xargs -r -0 git rm --ignore-unmatch

That way, if ls-files shows nothing, xargs won't call git rm at all.

orip
+2  A: 

With a git reset --hard before it, the git ls-files -d should never generate any output (and if it did, you would want to use git ls-files -d -z to have it produce NUL-terminated output for xargs -0).

Once you have done git reset --hard, the tracked portion of the working tree and the whole index will match the HEAD commit. git ls-files -d will only show files that are in the index but not in the working tree. Since the working tree will have everthing that the index has, there should never be any deleted files after a hard reset.

The git clean bit is useful to delete untracked files (which git reset --hard will not touch), but you might want to change it to git clean -dfq to also delete wholly untracked directories).

Chris Johnsen
Ahhh, okay - I see. Trying to do too much at once, it seems.
ABach