# This would output the total number of elements in the array, ... 4:
echo ${my_array[@]}
This is inaccurate. If you used echo "${#my_array[@]}" you get 4. As written, you get value 1 value 2 value 3 value 4, and that's 8 arguments to echo, as you would see if you used printf '%s\n' ${my_array[@]} instead. You'd get 4 arguments if you used printf '%s\n' "${my_array[@]}", and 1 argument if you used printf '%s\n' "${my_array[*]}", but 8 again if you omitted the double quotes with the * notation. Using both printf '%s\n' ${#my_array[*]} and printf '%s\n' ${#my_array[@]} (without double quotes around the array references) also prints 4 both times. Usually, you should use double quotes around array references.
I am a professional DevOps Engineer with a demonstrated history of working in the internet industry. I am an avid Linux lover and supporter of the open-source movement philosophy.
Location
Sofia, Bulgaria
Work
Developer Advocate at Materialize | Community Manager at DigitalOcean | Co-Founder at DevDojo
Under Arrays, you have:
# This would output the total number of elements in the array, ... 4:
echo ${my_array[@]}
This is inaccurate. If you used
echo "${#my_array[@]}"
you get 4. As written, you getvalue 1 value 2 value 3 value 4
, and that's 8 arguments toecho
, as you would see if you usedprintf '%s\n' ${my_array[@]}
instead. You'd get 4 arguments if you usedprintf '%s\n' "${my_array[@]}"
, and 1 argument if you usedprintf '%s\n' "${my_array[*]}"
, but 8 again if you omitted the double quotes with the*
notation. Using bothprintf '%s\n' ${#my_array[*]}
andprintf '%s\n' ${#my_array[@]}
(without double quotes around the array references) also prints4
both times. Usually, you should use double quotes around array references.Thank you for bringing this up!
Indeed I've missed the
#
sign in the example for getting the lenght of the array. I've added it now.The printf examples that you've show are really great!