'One-liner to check whether a file exists, then feed it to xargs

I have a one-liner that spits out all of the files modified in my current feature branch, which is branched off of a shared, upstream development branch. I then hope to feed the files that exist to the phpcs linter via xargs -- something like this:

git diff --name-only shared-upstream-development-branch | grep "\.php$" | xargs test -f {} && echo {} | xargs vendor/bin/phpcs

However, when I run this, I get something like the following:

test: extra argument ‘path/to/my/file.php’

I feel like I'm close to having a working solution.

How can I modify the one-liner above to correctly see if each PHP file still exists, then feed it onward to phpcs?

I know that everything up through the output of the grep command works well, as removing the two parts of the one-liner that refer to xargs gives me a nice list of file names.

(I also tried using --diff-filter=d to filter out deleted files, but this does not seem to work with my version of git, as I still get a complaint from phpcs about how a file "does not exist.")



Solution 1:[1]

&& separates commands, and is not an argument to xargs; you need to execute an explicit shell to use &&.

xargs sh -c 'test -f "$1" && echo "$1"' _ {}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chepner