1

On bash shell. I am trying to give variable length of an array in for loop range and print all the elements one by one till last element. My code looks like this

for a in {0..$((${#array[@]}))}; do
   echo "${array[$a]}"
done

getting below error while executing script

line 14: {0..9}: syntax error: operand expected (error token is "{0..9}")

How to convert length of array into a integer? Thanks in advance!

anubhava
  • 761,203
  • 64
  • 569
  • 643
Satz
  • 13
  • 3

1 Answers1

-1
for a in `eval echo {0..$((${#array[@]}-1))}`
do
  # do stufff with $a like echo ${array[$a]}
done

should be fine.. Mind that the count starts from 0 to total-1 and that is what is done in using
$(( )).

sjsam
  • 21,411
  • 5
  • 55
  • 102
  • 1
    Don't you think it is a unsafe practice of recommending to use `eval` when you can just use the arithmetic context operator.? `for ((i=0; i < ${#array[@]}; i++))` – Inian Nov 09 '17 at 11:59
  • both method worked fine. Thank you :) – Satz Nov 09 '17 at 12:20
  • @Inian : The use of can be unsafe in certain circumstances, especially when it accepts value from user. But as of here, it is pretty straight forward though a bit unreadable.. But that said `c-style` for loop is the more readable and is recommended. – sjsam Nov 09 '17 at 12:31
  • 1
    Just to be clear, I didn’t downvote the answer ;) my emphasis was to not recommend such a practice. Agree using eval is not that dangerous here. – Inian Nov 09 '17 at 12:34