oz1cz
oz1cz

Reputation: 5824

bash command output as parameters

Assume that the command alpha produces this output:

a b c
d

If I run the command

beta $(alpha)

then beta will be executed with four parameters, "a", "b", "c" and "d".

But if I run the command

beta "$(alpha)"

then beta will be executed with one parameter, "a b c d".

What should I write in order to execute beta with two parameters, "a b c" and "d". That is, how do I force $(alpha) to return one parameter per output line from alpha?

Upvotes: 4

Views: 268

Answers (4)

chepner
chepner

Reputation: 530960

Similar to anubhava's answer, if you are using bash 4 or later.

readarray -t args < <(alpha)
beta "${args[@]}"

Upvotes: 4

anubhava
anubhava

Reputation: 784998

Do that in 2 steps in bash:

IFS=$'\n' read -d '' a b < <(alpha)

beta "$a" "$b"

Example:

# set IFS to \n with -d'' to read 2 values in a and b
IFS=$'\n' read -d '' a b < <(echo $'a b c\nd')

# check a and b
declare -p a b
declare -- a="a b c"
declare -- b="d"

Upvotes: 2

yolenoyer
yolenoyer

Reputation: 9445

You can use:

$ alpha | xargs -d "\n" beta

Upvotes: 8

aicastell
aicastell

Reputation: 2392

Script beta.sh should fix your issue:

$ cat alpha.sh
#! /bin/sh
echo -e "a b c\nd"

$ cat beta.sh
#! /bin/sh
OIFS="$IFS"
IFS=$'\n'
for i in $(./alpha.sh); do
    echo $i
done

Upvotes: -1

Related Questions