0

I need to test to see if bash variables have something in them or if they are empty.

I am writing a script that rotates aws keys.

I came up with this test:

keys=$(aws iam list-access-keys --user-name "$user_name" --profile="$aws_key"  | grep -i accesskeyid | awk '{print $2}' | sed 's/"//g')
   key1=${keys%$'\n'*}
   key2=${keys#*$'\n'}

   echo "$key1"
   echo "$key2"
   echo

   if [[ "$key1" != "^$" ]]; then
     echo "Key1: $key1"
   elif [[ "$key2" != "^$" ]]; then
     echo "Key 2: $key2"
   else 
     echo "There is no key data."
   fi

And when I run the script it first prints the two variables to assure they have values. But when I run the test to see if they have values, only the first variable prints out:

AKIAIDQFZ62EMKNSZ7PQ
AKIAIPSNLAJKBLH2CLOQ

Key1: AKIAIDQFZ53EMKNSZ7PQ

How can I effectively test the contents of variables key1 and key2 to be sure they have contents?

Reason for this is that AWS users may have one or two keys, and can vary by user.

bluethundr
  • 1,005
  • 17
  • 68
  • 141
  • If you want a regex match, you need to use `=~`, not `=` or `!=`, and leave the right-hand side unquoted (in `[[ ]]`, quotes are optional on the left-hand side). Thus, `if ! [[ $key1 =~ ^$ ]]; then` is a long-winded regex-based way of writing `if [[ $key1 ]]` or `if [ -n "$key1" ]` – Charles Duffy Jun 04 '18 at 20:04
  • I suggest you use the array approach from my answer to your other question, which then lets you just check array elements. – Benjamin W. Jun 04 '18 at 20:11

1 Answers1

1

Your logic is incorrect. You check the first key with if [[ "$key1" != "^$" ]]; then. If that is true, then we exit the if statement. elif [[ "$key2" != "^$" ]]; then only runs if the first check was false. (elif is short for else if). You would correctly reach your else statement in this case, but you are going to skip over the elif if the first condition is met.

Your logic should look like this:

if [[ $key1 ]]; then
  echo "Key1: $key1"
fi

if [[ $key2 ]]; then
  echo "Key 2: $key2"
fi

if [[ ! $key2$key1 ]]; then
  echo "There is no key data."
fi

Edit: Fixed if block according to Charles' suggestion. Honestly, didn't know that was a Bashism. I only really use Bash =D.

Jason
  • 2,493
  • 2
  • 27
  • 27