Bash command output as parameters

Suppose the command alphaproduces this output:

a b c
d

If I run the command

beta $(alpha)

then betait is performed with four parameters "a", "b", "c"and "d".

But if I run the command

beta "$(alpha)"

it betawill be executed with a single parameter "a b c d".

What should I write to perform betawith two parameters, "a b c"and "d". That is, how to $(alpha)get one parameter to be returned to the output string from alpha?

+4
source share
4 answers

As for anubhava answer if you are using bash4 or later.

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

:

$ alpha | xargs -d "\n" beta
+7

2 bash:

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

beta "$a" "$b"

:

# 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"
+2

Script beta.sh :

$ 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
-1

Source: https://habr.com/ru/post/1672471/


All Articles