How to pass pipe output as argument to a command

When working with shell scripting tasks, one often encounters situation where one command’s output need to be passed to another command and in such situation typically pipe feature is used.

Code:

ls -1|wc -l

The above example will list the number of files in the current directory.

If you want to pass the filename as command line argument instead of passing it to stdin, then the below method should be used.

ls -1|xargs -n 1 echo "The file name is" $1

Here the output of ls -1 will be passed as a command line argument to the echo.
For more information refer to main page or wiki page of xargs.

Leave a Reply

Your email address will not be published. Required fields are marked *