Search code examples
bashfindxargs

Connecting find -print0 and xargs -0


find parameter -print0 and xargs parameter -0 are expected to work together. man page of find says:

-print0 .... This option corresponds to the -0 option of xargs.

Well, they work for me as long as find produces some output. How can I get it to work when find produces NO output?

find /dev /sys /usr -maxdepth 0 -print0 | xargs -0 -n1 | wc -l    # 3 - OK
find /dev /sys -maxdepth 0 -print0 | xargs -0 -n1 | wc -l         # 2 - OK
find /dev -maxdepth 0 -print0 | xargs -0 -n1 | wc -l              # 1 - OK
find /dev -maxdepth 0 -name "x" -print0 | xargs -0 -n1 | wc -l    # 1 instead of 0 - Fail

Some bad things may happen, for example,

find -type d -name ... -print0 | xargs -0 du -sh

when no directories are found xargs invokes du without arguments and du assumes .

P.S. I know about -exec parameter of find, I just want to connect find and xargs properly.


Solution

  • GNU xargs features the following option:

      --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.