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
4
  • 1
    Not an exact duplicate, but you can use the technique from the answer to this question. Commented Dec 12, 2018 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). Commented Dec 12, 2018 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. Commented Dec 12, 2018 at 16:13
  • @CharlesDuffy Thank you, I'll keep it in mind Commented Dec 12, 2018 at 16:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Love the nameref control variable ;)
Yup, you brought me around on that one :)
thank you I was just looking for something like that and it's going to be useful for the project I'm doing I was already going crazy with trying
Hmmm, using declare -n curSrv, echo "${#srvVar[@]}" isn't going to do much... (typo -- welcome to the human race :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.