我试图通过for循环读取命令的输出,但是这样循环变量将是一个数组。那可能吗? 这是我到目前为止所尝试的:
function samplevals() {
echo '"aa bb"'
echo '"cc dd"'
echo '"ee ff" "gg hh"'
}
samplevar='"aa bb"
"cc dd"
"ee ff" "gg hh"'
echo call function samplevals:
for x in `samplevals `; do echo ">$x<"; done
echo read variable samplevar:
echo $samplevar
for x in $samplevar; do echo ">$x<"; done
echo process output of 'echo samplevar:'
for x in `echo $samplevar`; do echo ">$x<"; done
echo "the thing with set"
for x in $samplevar; do set -- $x ; echo "\$1=>$1<,\$2=>$2<"; done
但输出始终相同:
>"aa<
>bb"<
>"cc<
>dd"<
>"ee<
>ff"<
>"gg<
>hh"<
我可以以某种方式阻止bash将元素拆分成更小的部分吗?
答案 0 :(得分:1)
在bash
中定义数组的方法是
samplevars=("aa bb" "cc dd" "ee ff" "gg hh")
for x in "${samplevars[@]}"; do
echo ">$x<"
done
答案 1 :(得分:1)
沿chepner's answer行,使用read
命令。命令的-a
标志部分允许输出写出到数组。
IFS=$'\t' read -ra arrayDef < <(echo -ne '"abc def"\t"ghi jkl"')
for x in "${arrayDef[@]}"; do
echo ">$x<"
done
您可以使用生成此类字符串的某个命令替换echo
部分。请记住适当更新IFS
字符串的限制方式。就我而言,我只是将字符串限制为\t