Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 使用间接寻址的数组操作_Arrays_Linux_Bash - Fatal编程技术网

Arrays 使用间接寻址的数组操作

Arrays 使用间接寻址的数组操作,arrays,linux,bash,Arrays,Linux,Bash,在使用间接${!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

在使用间接
${!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[@]}”
,这就是使用正确的引号对具有该名称的数组进行寻址的方式

不幸的是,没有通过间接寻址直接引用数组的方法,但请参阅以了解一些解决方法

还要注意怎么做

y3=()
不同于

y3=
对实际上不是变量的东西使用变量也有点代码味道

#/bin/bash
i=“1 2 3”
x=CONFIG
y1=(“A和B”“B和C”)
y2=(“ABC和D”)
#修正y3赋值
y3=()
回显“y1=${y1[@]}”
回显“y2=${y2[@]}”
回显“y3=${y3[@]}”
回声“==”
以$i表示的z
做
#在Aaron对链接问题的回答中添加[@]
t=y${z}[@]
#并且(总是!)引用变量插值
tval=(“${!t}”)
r=0
echo“在${t}中有${tval[@]}个元素。”
如果[${tval[@]}-gt 0];然后
r=1
echo“config\u y${z}=\”
fi
对于“${tval[@]}”中的电视
做
[-n“${tv}]”和&echo“${tv}”
完成
如果[“x$r”=“x1”];则
回音“\”
fi
完成

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

这也可能对您有所帮助:如您所见,注释中的代码实际上不起作用。当然,如果您愿意,您可以使用另一个免费变量,但我建议不要对您的私有变量使用大写。