dimanche 26 juin 2016

If statement with multiple null string comparisons, print error with the ones that fail

Let's say I have the following if statement that checks multiple variables

if [[ -z ${var1} || -z ${var2} || -z ${var3} ]]; then
   echo "Error, one or more variables are empty"
   exit 2
fi

I'm looking for a way in which I can do the same test, but somehow be able to print the exact variables that are empty, something like this:

if [[ -z ${var1} || -z ${var2} || -z ${var3} ]]; then
   echo "Error, the following variables are empty: ${var1} and ${var3}"
   exit 2
fi

Of course, I could test them individually:

if [[ -z ${var1} ]]; then
   echo "Error, the following variable is empty: ${var1}"
   exit 2
fi
if [[ -z ${var2} ]]; then
   echo "Error, the following variable is empty: ${var2}"
   exit 2
fi
if [[ -z ${var3} ]]; then
   echo "Error, the following variable is empty: ${var3}"
   exit 2
fi

But this method also has a big flaw: if there are multiple empty variables, the script will exit after the first one, you'll never know that others are also empty.

Aucun commentaire:

Enregistrer un commentaire