输出

输出

对于我正在制作的脚本,我需要将命令的输出转换为数组。为了简化,我用 echo 做了一个例子:

arr=( $(echo '"test example" "test2 example"') )

我想要的是数组的第一个元素

test example

但是当这样做时:

echo ${arr[0]}

我明白了

"test

我必须做什么才能得到我想要的结果?

答案1

认为回声不能像命令一样产生正确的输出,因此必须包括sed

mapfile -t arr < <(
    echo '"test example1" "test2 example2"' |
    sed 's/" "/"\n"/g'
)

答案2

eval "arr=( $(echo '"test example" "test2 example"') )"

echo "${arr[0]}"

for e in "${arr[@]}"; do
   echo "<$e>"
done

输出

test example

<test example>
<test2 example>

相关内容