Search code examples
arraysbashmaxmaxlengthassociative

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


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

Solution

  • 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