0

I use following code to verify if variable is not empty and this works fine

VAR=(var1 var2 var3)

chec_var() { for item in "${@}"; do if [ -z "${!item}" ]; then returncode=1 break else returncode=0 fi done }

all_vars() { if chec_var "${VAR[@]}"; then if [[ ${returncode} -gt 0 ]]; then echo "error" exit 1 else echo "OK" fi fi }

all_vars

The problem stars when I add set -Euo pipefail at the end of the script.
Than when one of variables is not present I get following error:
/script line number: !item unbound variable
but it should display "echo error" instead message from pipefail

Another time when all variables are present than it checks only first variable and displays
"echo OK"
instead of going through the loop and check all variables

Question:
What am I doing wrong here?
How to loop through all variables and once all are check to display OK when -Euo pipefail is enabled?

Modified script with pipefail looks as following:

VAR=(var1 var2 var3)

chec_var() { for item in "${@}"; do if [ -z "${!item}" ]; then return 1 break else return 0 fi done }

all_vars() { if chec_var "${VAR[@]}"; then if [[ ${returncode} -gt 0 ]]; then echo "error" exit 1 else echo "OK" fi fi }

set -Euo pipefail

all_vars

1 Answers1

1

here's one way to do it in bash:

if declare -p variable >&/dev/null ; then
  echo "variable exists"
else
  echo "variable does not exist"
if

declare -p will return with an exit code of 0 if the variable exists, and 1 if it doesn't. The redirection of stdout and stderr is because we don't want to see any output, we just want to test if the variable exists.

In most cases, though, just testing if the variable is empty (i.e. [ -z "$variable" ] or, invert the test for not-empty, with [ -n "$variable" ]) is good enough.

cas
  • 78,579
  • [ -n "$variable" ] or [ -z "$variable" ] would trip set -o nounset aka set -u if the variable is unset as that's still a attempt at dereferencing it. Using the ${variable+set} parameter expansion operator cancels the set -o nounset effect. – Stéphane Chazelas Aug 12 '21 at 16:17
  • That's part of the reason why I said "in most cases". set -o nounset isn't "most cases". – cas Aug 12 '21 at 16:42
  • Yes, but the question is "how do you do it with set -u", so, it's actually "in most cases, but not yours". – Stéphane Chazelas Aug 13 '21 at 07:12
  • ya know, that's why it was an aside at the end of my answer, not my actual answer. – cas Aug 13 '21 at 07:53