0

I have filled an array foo$i with values and have set i=4 (but i could be anything). How can I get the length of this array? The command ${#foo4[@]} works, but ${#foo$i[@]} doesn't. How can I find the length if the name of the array has a variable?

1
  • Didn't I just answer this for you in a comment on a different question? Commented Apr 9, 2014 at 4:18

1 Answer 1

3

With bash 4.3, there's a new feature, namerefs, which allows this to be done safely:

i=4
foo4=( hello cruel world )
declare -n foo_cur="foo$i"
foo_count=${#foo_cur[@]}
echo "$foo_count"

Prior to bash 4.3, you need to use eval (despite its propensity for causing bugs):

i=4
foo4=( hello cruel world )
eval 'foo_count=${#foo'"$i"'[@]}'
echo "$foo_count"

...yields the correct answer of 3.

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

1 Comment

Of course. You could, for instance, substitute "$(eval 'echo ${#foo'"$i"'[@]}')" somewhere within a larger command. That said, subshells introduce inefficiency, so using them without cause is silly.

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.