问题
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?
回答1:
Similar to anubhava's answer, if you are using bash 4 or later.
readarray -t args < <(alpha)
beta "${args[@]}"
回答2:
You can use:
$ alpha | xargs -d "\n" beta
回答3:
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"
回答4:
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
来源:https://stackoverflow.com/questions/42836355/bash-command-output-as-parameters