user2064000
user2064000

Reputation:

Testing empty variables

I have a large number of variables in my script, and I want the script to error out if any one of the variables are empty.

I know I can:

if [[ -z "$var_1" ]] || [[ -z "$var_2" ]] || ... [[ -z "$var_n" ]]; then
  # failure message
fi

However, I cannot inform the user which variable was empty if I do it in this way. Is there an alternative approach to the above so that I can inform the user about the empty variable?

Upvotes: 0

Views: 58

Answers (2)

Zombo
Zombo

Reputation: 1

#!/bin/sh
foo=(var_1 var_2 var_n)

for bar in ${foo[*]}
do
  if [[ ! ${!bar} ]]
  then
    echo $bar is empty
  fi
done

Upvotes: 2

William Pursell
William Pursell

Reputation: 212158

Just use ${var:?var is empty or unset} the first time you reference the variable. If empty strings are acceptable and you only care if the variables are set, do ${var?var is unset}. Using ? in the parameter expansion causes the shell to terminate and if the variable is (empty or) unset.

Upvotes: 1

Related Questions