mardi 30 octobre 2018

Determine if Array Has Elements in IF/Then Statement In Bash

I'm trying to determine if an array has elements in an if/then statement like this:

if [[ -n "$aws_user_group" && -n "${#aws_user_roles[@]}" ]]; then
  echo "$aws_user_name,$aws_user_group,"${aws_user_roles[*]}",$aws_key,$aws_account_number" >> "$ofile"
 elif [[ -n "$aws_user_group" ]]; then
  echo "$aws_user_name,$aws_user_group,,$aws_key,$aws_account_number" >> "$ofile"
fi 

Problem is, if the array is empty it's represented by '0' as in this debug output:

   [[ -n 0 ]]

And the wrong line prints out. It prints the line that includes the 'role' output but leaves it blank.

How can I more effectively check if the array has elements so that it doesn't pass the check if the array is empty?

Aucun commentaire:

Enregistrer un commentaire