How to pass command output as several arguments to another command

I have a command that produce a output like this:

$./command1
word1 word2 word3

I want to pass this three words as arguments to another command like this:

$ command2 word1 word2 word3

How to pass command1 output as three different arguments $1 $2 $3 to command2 ?


Solution 1:

You can use xargs, with the -t flag xargs will be verbose and prints the commands it executes:

./command1 | xargs -t -n1 command2

-n1 defines the maximum arguments passed to every call of command2. This will execute:

command2 word1
command2 word2
command2 word3

If you want all as argument of one call of command2 use that:

./command1 | xargs -t command2

That calls command2 with 3 arguments:

command2 word1 word2 word3

Solution 2:

You want 'command substitution', i.e: embed output of one command in anouther

command2 $(command1)

Traditionally this can also be done as:

command2 `command1`

but this usage isn't normally recommended, as you can't nest them.

For example:

test.sh:
#!/bin/bash
echo a b c

test2.sh

#!/bin/bash
echo $2

USE:

./test2.sh $(./test.sh)
b