在bash中使用for循环时如何获取二维数组的值?
how to get value of two dimension of array when using for loop in bash?
下面是我的代码,我的问题是如何获取for循环体中的值?
#!/bin/bash
ar1=("moneyclub8.com" "fwdv4u")
ar2=("ghist2811.com" "n9dv03")
ar3=("ghost.com" "eccsml")
arr=(ar1 ar2 ar3);
for data in "${arr[@]}" ; do
reallist=$data[@]
domain= "" ##<== how to get value here ?
code= "" ##<== how to get value here ?
for key in "${!reallist}" ; do
echo "the key is: $key"
done
done
动态数组引用的一个想法是使用 nameref
(declare -n
):
#!/usr/bin/bash
ar1=("moneyclub8.com" "fwdv4u")
ar2=("ghist2811.com" "n9dv03")
ar3=("ghost.com" "eccsml")
arr=(ar1 ar2 ar3);
for data in "${arr[@]}" ; do
declare -n reallist=$data # use nameref to access underlying array
domain="${reallist[0]}" # see output from "typeset -p ar1 ar2 ar3"
code="${reallist[1]}" # to validate these references
typeset -p domain code # display content of variables
for key in "${!reallist[@]}" ; do # added "[@]" to provide access to array indices
echo "the key is: $key"
done
done
运行 此脚本生成:
declare -- domain="moneyclub8.com"
declare -- code="fwdv4u"
the key is: 0
the key is: 1
declare -- domain="ghist2811.com"
declare -- code="n9dv03"
the key is: 0
the key is: 1
declare -- domain="ghost.com"
declare -- code="eccsml"
the key is: 0
the key is: 1
下面是我的代码,我的问题是如何获取for循环体中的值?
#!/bin/bash
ar1=("moneyclub8.com" "fwdv4u")
ar2=("ghist2811.com" "n9dv03")
ar3=("ghost.com" "eccsml")
arr=(ar1 ar2 ar3);
for data in "${arr[@]}" ; do
reallist=$data[@]
domain= "" ##<== how to get value here ?
code= "" ##<== how to get value here ?
for key in "${!reallist}" ; do
echo "the key is: $key"
done
done
动态数组引用的一个想法是使用 nameref
(declare -n
):
#!/usr/bin/bash
ar1=("moneyclub8.com" "fwdv4u")
ar2=("ghist2811.com" "n9dv03")
ar3=("ghost.com" "eccsml")
arr=(ar1 ar2 ar3);
for data in "${arr[@]}" ; do
declare -n reallist=$data # use nameref to access underlying array
domain="${reallist[0]}" # see output from "typeset -p ar1 ar2 ar3"
code="${reallist[1]}" # to validate these references
typeset -p domain code # display content of variables
for key in "${!reallist[@]}" ; do # added "[@]" to provide access to array indices
echo "the key is: $key"
done
done
运行 此脚本生成:
declare -- domain="moneyclub8.com"
declare -- code="fwdv4u"
the key is: 0
the key is: 1
declare -- domain="ghist2811.com"
declare -- code="n9dv03"
the key is: 0
the key is: 1
declare -- domain="ghost.com"
declare -- code="eccsml"
the key is: 0
the key is: 1