【发布时间】:2020-03-21 16:22:04
【问题描述】:
在使用间接${!varname} 时,我想在 BASH 中正确使用数组。
这是我的示例脚本:
#!/bin/bash
i="1 2 3"
x=CONFIG
y1=( "A and B" "B and C" )
# y1=( "\"A and B\"" "\"B and C\"" )
y2=( "ABC and D" )
y3=
echo "y1=${y1[@]}"
echo "y2=${y2[@]}"
echo "y3=${y3[@]}"
echo "==="
for z in $i
do
t=y${z}
tval=( ${!t} )
r=0
echo "There are ${#tval[@]} elements in ${t}."
if [ ${#tval[@]} -gt 0 ]; then
r=1
echo "config_y${z}=\""
fi
for tv in "${tval[@]}"
do
[ -n "${tv}" ] && echo "${tv}"
done
if [ "x$r" == "x1" ]; then
echo "\""
fi
done
结果如下:
y1=A and B B and C
y2=ABC and D
y3=
===
There are 3 elements in y1.
config_y1="
A
and
B
"
There are 3 elements in y2.
config_y2="
ABC
and
D
"
There are 0 elements in y3.
我想得到的是:
y1=A and B B and C
y2=ABC and D
y3=
===
There are 2 elements in y1.
config_y1="
A and B
B and C
"
There are 1 elements in y2.
config_y2="
ABC and D
"
There are 0 elements in y3.
我也尝试过这样的运行:
#!/bin/bash
i="1 2 3"
x=CONFIG
y1=( "A and B" "B and C" )
# y1=( "\"A and B\"" "\"B and C\"" )
y2=( "ABC and D" )
y3=
for variable in ${!y@}
do
echo "$variable" # This is the content of $variable
echo "${variable[@]}" # So is this
echo "${!variable}" # This shows first element of the indexed array
echo "${!variable[@]}" # Not what I wanted
echo "${!variable[0]} ${!variable[1]}" # Not what I wanted
echo "---"
done
理想情况下,${!Variable[@]} 应该做我想做的事,但事实并非如此。
另外,${!Variable} 只显示数组的第一个元素,
我可以尝试什么?
【问题讨论】:
-
这也可能对您有所帮助:mywiki.wooledge.org/BashFAQ/006