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?
-
Didn't I just answer this for you in a comment on a different question?Charles Duffy– Charles Duffy2014-04-09 04:18:08 +00:00Commented Apr 9, 2014 at 4:18
Add a comment
|
1 Answer
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.
1 Comment
Charles Duffy
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.