0

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 check a string variable and a mathematical variable in the same if/then statement?

1
  • -n and -z are non-zero and zero length strings, not for mathematical comparisons. Commented Oct 30, 2018 at 18:48

1 Answer 1

2

Zero is the number of elements. Use a mathematical evaluation.

if (( ${#aws_user_roles[@]} )) # HAS ELEMENTS
then echo has elements
else echo is empty
fi

example

$: declare -i foo=()
$: if (( ${#foo[@]})); then echo elements; else echo empty; fi
empty
$: foo=( 1 2 3 )
$: if (( ${#foo[@]})); then echo elements; else echo empty; fi
elements

as an aside...

$: foo=( 1 2 3 )
$: if (( ${#foo})); then echo elements; else echo empty; fi
elements

also works, but ${#foo} is really only looking at the string length of first element, and could theoretically give you a false response...though '' returns 1. Hmm...

You can also chain tests for other things -

if (( ${#var} )) && [[ -e "$var" ]] # both must succeed

This is the same as one-liner tests

ls a && ls b || echo one of these doesn't exist...
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, thanks. Any way to combine the mathematical test with the test to see if the other variable with text has a value: -n "$aws_user_group" ?
just use && between your tests. See above.
Ok thanks. Also I tried this and it works: if [[ -n "$aws_user_group" && -n "${aws_user_roles[@]}" ]]; then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.