使用间接寻址的数组操作



我想在使用间接寻址${!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}只显示数组的第一个元素,

我可以尝试什么?

您访问数组的语法在这里是错误的:

tval=( ${!t} )

这将评估为例如$y1但你想要"${y1[@]}"这就是你如何用适当的引号来称呼具有该名称的数组。

遗憾的是,没有直接的方法可以通过间接寻址引用数组,但请参阅在 bash 中间接引用数组值以获取一些解决方法。

还要注意如何

y3=()

不同于

y3=

对实际上不是变量的东西使用变量也是一种代码气味。

#!/bin/bash
i="1 2 3"
x=CONFIG
y1=( "A and B" "B and C" )
y2=( "ABC and D" )
# Fix y3 assignment
y3=()
echo "y1=${y1[@]}"
echo "y2=${y2[@]}"
echo "y3=${y3[@]}"
echo "==="
for z in $i
do
# Add [@] as in Aaron's answer to the linked question
t=y${z}[@]
# And (always!) quote the variable interpolation
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

可能还会调查明确打印值printf

最新更新