Saturday, February 1, 2014

xargs prints file names even if there are no matching files

A problem I faced with xargs command is that, it just lists the files/directories in the current directory if there is no input for the xargs command.

Let me illustrate with an example

In my current directory, I have just *.txt files

$ ls
abc.txt  ver1.txt  ver1.txt.orig  ver2.txt

When I try to fetch files with names of type *.jpg, I expected to get no output when I ran xargs with ls. But it printed all the file names in the current directory.

$ find . -type f -iname "*.jpg" | xargs ls
abc.txt ver1.txt  ver1.txt.orig  ver2.txt

The reason seems to be that, by default the command executed by xargs is /bin/echo and it will simply display file/directory names.

Later I found that, there exists an option "-r" for xargs, which did the trick for me

$ find . -type f -iname "*.jpg" | xargs -r ls


No comments:

Post a Comment