Bash: Is there a built-in way to get the maximum length of the keys in an associative array

1k Views Asked by At

In Bash, given an associative array, how do I find the length of the longest key?

Say, I declare myArray as shown below:

$  declare -A myArray=([zero]=nothing [one]='just one' [multiple]='many many')
$  echo ${myArray[zero]}
nothing
$  echo ${myArray[one]}
just one
$  echo ${myArray[multiple]}
many many
$

I can get it using the below one-liner

$  vSpacePad=`for keys in "${!myArray[@]}"; do echo $keys; done | awk '{print length, $0}' | sort -nr | head -1 | awk '{print $1}'`;
$  echo $vSpacePad
8
$

Am looking for something simpler like below, but unfortunately, these just give the count of items in the array.

$  echo "${#myArray[@]}"
3
$  echo "${#myArray[*]}"
3
2

There are 2 best solutions below

3
KamilCuk On BEST ANSWER

Is there a built-in way to get the maximum length of the keys in an associative array

No.

how do I find the length of the longest key?

Iterate over array elements, get the element length and keep the biggest number.

Do not use backticks `. Use $(..) instead.

Quote variable expansions - don't echo $keys, do echo "$keys". Prefer printf to echo.

If array elements do not have newlines and other fishy characters, you could:

printf "%s\n" "${myArray[@]}" | wc -L
2
glenn jackman On

You do need to loop over the keys, but you don't need any external tools:

max=-1
for key in "${!myArray[@]}"; do
  len=${#key}
  ((len > max)) && max=$len
done
echo $max    # => 8

If you want to print the elements of an array one per line, you don't need a loop: printf is your friend:

printf '%s\n' "${!myArray[@]}"

printf iterates until all the arguments are consumed