14

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 ?

BenMorel
  • 4,215
  • 10
  • 53
  • 81
Addy
  • 161
  • 1
  • 1
  • 5

3 Answers3

11

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
chaos
  • 1,445
  • 1
  • 14
  • 21
  • What if the output of command1 is longer than `ARG_MAX` ? I have a scenario where I am passing contents of a file to a function. – 0xc0de Feb 19 '19 at 11:29
  • Big thanks ! the -n1 option saved the day ! Below is the commands I was trying jq -r '.repositories[].repositoryUri' | xargs -t -n1 docker pull – Rohit Salecha Feb 09 '21 at 12:33
4

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
Barmar
  • 344
  • 1
  • 8
Sirex
  • 5,447
  • 2
  • 32
  • 54
  • If I do that, it is passing command1 output as one single argument, not like three different: $command2 $(cat output_from_command1) – Addy Nov 04 '14 at 18:45
  • ah right, one sec... btw cat isn't needed in that one you put there. – Sirex Nov 04 '14 at 18:47
  • Works for me. If my command2 echos $2 (i,e: second argument) i get "word2" as expected. – Sirex Nov 04 '14 at 18:49
0

I guess this help you

command1 | xargs command2

PoLIVoX
  • 185
  • 1
  • 1
  • 6