Looping over arrays, printing both index and value

前端 未结 6 1938
无人及你
无人及你 2020-12-07 07:35

I want to do something like this:

foo=( )
foo[0]=\"bar\"
foo[35]=\"baz\"
for((i=0;i<${#foo[@]};i++))
do
    echo \"$i: ${foo[$i]}\"
done
# Output:
# 0: ba         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 08:23

    You would find the array keys with "${!foo[@]}" (reference), so:

    for i in "${!foo[@]}"; do 
      printf "%s\t%s\n" "$i" "${foo[$i]}"
    done
    

    Which means that indices will be in $i while the elements themselves have to be accessed via ${foo[$i]}

提交回复
热议问题