I often print out the contents of an array using a quick printf shorthand like this:
$ printf "%s\n" "${my_array[@]}"
$ printf "%s\0" "${my_array[@]}"
This works great in general:
$ my_array=(limburger stilton wensleydale)
$ printf "%s\n" "${my_array[@]}"
limburger
stilton
wensleydale
$
Works great, but when the array is empty it still outputs a single character (a newline or null byte):
$ my_array=()
$ printf "%s\n" "${my_array[@]}"
$
Of course, I can avoid that by testing first for an empty array:
$ [[ ${#my_array[@]} -gt 0 ]] && printf "%s\n" "${my_array[@]}"
$ (( ${#my_array[@]} )) && printf "%s\n" "${my_array[@]}"
But I use this idiom all the time and would prefer to keep it as short as possible. Is there a better (shorter) solution, maybe a different printf format, that won't print anything at all with an empty array?
printffills in missing arguments. For example, with a quote spec, it prints the empty string:printf '%q\n'->''; and with a number spec, it prints zero:printf '%d\n'->0orprintf '%d %d\n' 5->5 0.(( ${#my_array[@]} ))fails in aset -econtext. Instead, you may want the equivalent:(( ${#my_array[@]} == 0 )) || printf "%s\n" "${my_array[@]}"