bash command output as parameters

夙愿已清 提交于 2019-12-10 15:30:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!