How can I use -0 option to xargs when specifying the input manually?

Ankur Agarwal picture Ankur Agarwal · May 25, 2011 · Viewed 11.7k times · Source

I have

~/bashpractice$ ls
dir3 dir1   

I get

~/bashpractice$ xargs ls -l 
dir1 dir3
dir1:
total 0
-rw-r--r-- 1 abc abc 0 2011-05-23 10:19 file1
-rw-r--r-- 1 abc abc 0 2011-05-23 10:19 file2

dir3:
total 0
-rw-r--r-- 1 abc abc 0 2011-05-23 10:20 file1
-rw-r--r-- 1 abc abc 0 2011-05-23 10:20 file2

But I get an error when I do

~/bashpractice$ xargs -0 ls -l
dir1 dir3
ls: cannot access dir1 dir3
: No such file or directory

abc@us-sjc1-922l:~/bashpractice$ xargs -0 ls -l
dir1
dir3 
ls: cannot access dir1
dir3
: No such file or directory

How to get a listing when specifying -0 option to xargs ?

Answer

jm666 picture jm666 · May 25, 2011

For example - as told in the man xargs

-0 Change xargs to expect NUL (``\0'') characters as separators, instead of spaces and newlines. This is expected to be used in concert with the -print0 function in find(1).

find . -print0 | xargs -0 echo

The -0 tells xargs one thing: "Don't separate input with spaces but with NULL char". It is useful usually in combination with find, when you need handle files and/or directories that contain space in their name.

There are more commands what can play with -print0 - for example grep -z.

Edit - based on comments:

See Seth's answer or this:

ls -1 | perl -pe 's/\n/\0/;' > null_padded_file.bin
xargs -0 < null_padded_file.bin

But it is strange, why want use -0 if you don't need to use it?. Like "Why want remove a file, if does not exist?". Simply, the -0 is needed to use only with combination, if the input is null-padded. Period. :)