Bash xargs – Use Anywhere in Your Command

If you want to use the xargs command to build a new command and place the standard input from your stream wherever you like (or in multiple places), here is an example:

Let’s say we have a hosts file:

111.222.111.222 host1.mydomain.com
222.111.222.111 host2.mydomain.com

We can take out the first column with awk (the IP column), and we can pipe it to xargs and use -I. Then we can use the % sign to both ssh to the IP and to display a message with the IP written from the host.

This is obviously very flexible and useful for pretty much any command you’re building from earlier inputs :).

cat dynamic_hosts | awk '{print $1}' | xargs -I % ssh % "echo hi from %"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s