-1

I have a command that produces output like this:

$ ./command1
word1 word2 word3 

I want to pass these 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?

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
Addy
  • 1
  • 3

2 Answers2

1

Just use an unquoted command substitution:

$ ./command2 $(./command1)

However, this also subjects the output of command1 to pathname generation, so if the output could include something like *.txt, you risk that being expanded to multiple words before being passed to command2. In that case, you'll need to use

$ read arg1 arg2 arg3 <<< "$(./command1)"
$ ./command2 "$arg1" "$arg2" "$arg3"

or

$ read -a args <<< "$(./command1)"
$ ./command2 "${args[@]}"

to split the output into 3 words without subjecting them to pathname generation.


This won't work if the output of command1 looks like

"word1a word1b" word2

and you expect to be able to pass two arguments, word1a word1b and word2 to command2, but getting that right is sufficiently tricky to require more details about what command1 could output to provide the correct solution.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • command1 produces output as plain text: hostname:port username password. command2 suppose to read three arguments again like hostname:port username password – Addy Nov 04 '14 at 18:52
  • In that case, I would recommend the version using `read`. I assume that neither the host, port, nor user-name can contain any whitespace, but I would hesitate to make any assumptions about the password. (It would fail if the password begins or ends with whitespace, but I seen no way to detect that from the described output of `command1` anyway). – chepner Nov 04 '14 at 19:12
0

seems the best way to separate the output from command1 and send it to command2 as three different arguments is to use xargs with -t option which is passing all as argument like this:

$ ./command1 | xargs -t command2

Source
https://serverfault.com/users/249134/chaosc

Community
  • 1
  • 1
Addy
  • 1
  • 3