bluethundr
bluethundr

Reputation: 1325

Read Number of Array Elements in Arithmetic Comparison using Bash

I am trying to see if an AWS user has more than one access key on an account. I get the number of access keys with this line:

readarray old_access_keys < <(aws iam list-access-keys --user-name "$aws_user_name" --profile="$aws_key" | jq -r '.AccessKeyMetadata[].AccessKeyId')

And if he has more than one access key, the script should return:

if (( "${!old_access_keys[@]}" > 1 )); then
    printf "User already has maximum keys allowed for this account.\\n\\n"
    return
  else
    ...some commands...
 fi

But when I run this script I get and error when I do that comparison:

./aws_key_utils.sh: line 480: ((: 0 1 > 1 : syntax error in expression (error token is "1 > 1 ")

How can I compare the number of elements in the array against 1 correctly?

Upvotes: 0

Views: 37

Answers (1)

anubhava
anubhava

Reputation: 785058

"${!old_access_keys[@]}" is wrong syntax to get number of elements in array. "${!old_access_keys[@]}" will return all indices (or keys in associative array) of array.

To get number of elements in array use:

if (( "${#old_access_keys[@]}" > 1 )); then
   printf "User already has maximum keys allowed for this account.\\n\\n"
fi

Upvotes: 2

Related Questions