What xargs does exactly?

I don't understand exactly what xargs does that's why I'm surprised why these 2 return different results:

find ~/Downloads -iname *btsync* | ls -al
find ~/Downloads -iname *btsync* | xargs ls -al

Why the first one doesn't return what I want? Instead it prints show all the files in the current directory.

3

1 Answer

Not all programs take input. The ls command can take a directory or a file as an argument (e.g. ls /etc) but you can't pipe (|) to it. So, the first command is the same as doing:

$ find ~/Downloads -iname *btsync*
$ ls -al

The pipe is ignored because ls has no way of reading from the standard input. xargs, on the other hand, does something completely different. It reads standard input and then runs the command you give it on each line of the input. From man xargs:

 This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial- arguments followed by items read from standard input. Blank lines on the standard input are ignored.

So, xargs will take each result of the find command and run ls on it which is what you want.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like