1

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
  • 1
    Not an exact duplicate, but you can use the technique from the answer to [this question](https://stackoverflow.com/q/53733286/3266847). – Benjamin W. Dec 12 '18 at 15:51
  • 1
    Aside: `eval $elt` introduces bugs you don't have with `eval "$elt"` (which still is error-prone, but not quite as much so). – Charles Duffy Dec 12 '18 at 15:56
  • 1
    ...to showcase a specific issue with `eval $elt` vs `eval "$elt"`, btw, try running `set -x; elt="array=( ' * ' )"; eval $elt; declare -p elt` in a non-empty directory. – Charles Duffy Dec 12 '18 at 16:13
  • @CharlesDuffy Thank you, I'll keep it in mind – Matias Angeluk Dec 12 '18 at 16:16

2 Answers2

4

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

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352