Why did using xargs fail in this case?

I tried to understand the usage of xargs and did the following experiment.

ls | xargs | touch

I want to refresh the files dates and directoris in the curent directory.

Though it is a bit silly,for I could use a simpler form to achieve the same effect.

In my mind, xargs reads from the STDIN and turn it into the arguments for the other command(/bin/echo by default if the command is not specified). Am I misunderstanding something?

It failed and I am wondering why.

Answer

It needs to be like this:

ls | xargs touch

The xargs command runs the touch command with a number of strings read from stdin. In your case, stdin for xargs is the output end of the pipe from ls.

The way you had the command:

ls | xargs | touch

xargs had no command to run against the strings (filenames) it would read from stdin. In that case, xargs simply prints each file name, and touch gets the list of file names on its standard input. But touch doesn’t read from its standard input, and since you didn’t give it any arguments, it should have printed an error message like:

touch: missing file operand
Try `touch --help' for more information.

(which you should have mentioned in your question).

Attribution
Source : Link , Question Author : xiaohan2012 , Answer Author : Keith Thompson

Leave a Comment