Using xargs command in Linux

The xargs command in a Unix-like system is used to build and execute commands from standard input. Through the use of xargs command, the output of a command is used as input to another command.

In this article, we will discuss the usage of xargs command in Linux along with some examples.

The syntax of xargs command in Linux

The syntax of using xargs command in Linux is given below –

xargs [options] command

OR you can use in combination with another command –

command1 | xargs command2

Where you can find a list of options that can be used with xargs command on its man page.

Usage of xargs command in Linux

The following example shows the usage of xargs command on a Linux system.

How to use xargs command with another command

The most basic use of xargs command is to take the output of a command and pass it as input to another command using xargs. You can see the given example –

echo "file1 file2 file3"  | xargs touch

Here all files will be pass as the argument to touch command which will create 3 files.

How to prompt for confirmation before executing a command

By using option -p with xargs command, you can make it prompt a user for confirmation. To proceed user can enter y else he can press n if he wants to decline.

For example –

echo "file1 file2 file3"  | xargs -p touch

How to run multiple commands using xargs

By using the option -I you can use multiple commands with xargs command. You can see the example which is given below –

echo "file1 file2 file3" | xargs -I % sh -c '{ touch %; ls -l %; }'

Here touch command will first create three files and then the ls command will display the list of files with permissions they have.

Example of using xargs with find command

The xargs command is most often used with the combination of the find command. You can use the find command to search for a specific file and then use xargs to perform the required operation.

For example, to find all the .jpeg files to a specific location on your system and then use the tar command to archive them we will use –

find Pictures/lalit/ -name "*.jpeg" -type f -print0 | xargs -0 tar -cvzf picture.tar.gz

Here -print0 will enable the printing of the full path on the terminal and -0 is used to terminate input items with a null character instead of whitespace.

How to read items from a file

If you use option -a or --arg-file with xargs then it will read input from a file instead of reading from standard input.

xargs -a rss_links.txt

Where rss_links.txt is a text file and using this command will display the content of this file.

Conclusion

There are similar other usages of xargs command. To know more about xargs read its man page and if you have a query then leave it in the comments below.

Leave a Comment