Reputation: 77
Example
I want to get the size of each arrangement. I have a multidimensional arrangement.
array=("SRV_1=(e1 e2 e3 e4)" "SRV_2=(e1 e2)")
for elt in "${array[@]}";do eval $elt;done
CANT_SRVS="${#array[@]}
for ((i=1;i<=$CANT_SRVS;i++));do
CANT_E="${#SRV_$i[@]}" <------ ERROR
echo $CANT_E <------- length array
done
Upvotes: 1
Views: 67
Reputation: 295288
A nameref can be pointed at multiple variables; thus making srvVar
refer to any of your multiple arrays below:
srv_1=(e1 e2 e3 e4) # I don't condone the original "eval" pattern, and no part of
srv_2=(e1 e2) # the question hinged on it; thus, not reproducing it here.
declare -n curSrv
for curSrv in "${!srv_@}"; do # iterates over variable names starting with "srv_"
echo "${#curSrv[@]}" # ...taking the length of each.
done
See this running at https://ideone.com/Js28eQ
Upvotes: 4
Reputation: 246744
Charles has very good advice.
A tangent on your code: in place of eval
, you can use declare
when you have a variable assignment saved in a variable.
value="SRV_1=(e1 e2 e3 e4)"
declare -a "$value"
varname=${value%%=*}
declare -p "$varname"
declare -a SRV_1='([0]="e1" [1]="e2" [2]="e3" [3]="e4")'
And, as Charles demonstrates, namerefs for working with the array: declare -n a=$varname
Upvotes: 0