0

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?

0

2 Answers 2

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

for bar in ${foo[*]}
do
  if [[ ! ${!bar} ]]
  then
    echo $bar is empty
  fi
done
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

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