DEV Community

Discussion on: The Only Bash Scripting Cheat Sheet That You Will Ever Need

Collapse
jonathan_leffler_336f14e5 profile image
Jonathan Leffler

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 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.

Collapse
bobbyiliev profile image
Bobby Iliev Author

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!