2

In a part of a bash script I'm writing, I'd like to check if any of the variables in a list are unset.

In Python, there is a built-in function all that returns True if all elements in an iterable are true:

>>> all([True, 1, "foo"])
True
>>> all([False, 1, "bar"])
False

Is there something similar in bash? Currently the way I'm doing this is by looping through each variable and setting a variable / breaking out of the loop if it encounters a variable that is null or an empty string, e.g.

$ b=1
$ c=""
$ d=2
$ a=( b c d )
$ any_false=0
$ for var in ${a[@]} ; do if [[ -z ${!var} ]] ; then any_false=1 ; break; fi ; done
$ echo $any_false
1

...but perhaps there's a more optimal way of checking this?

3cheesewheel
  • 9,133
  • 9
  • 39
  • 59
  • 1
    You are only testing if a variable has a non-null value, which is distinct from being truly unset. – chepner Sep 16 '13 at 23:46

2 Answers2

4

The for loop is the way to do it; there is no equivalent all construct in bash.

The Python docs show that these are equivalent: http://docs.python.org/2/library/functions.html#all

Remember, bash was designed to do one thing (shell operations) very well, so if you find yourself regularly needing higher level constructs, consider choosing a more full-featured language if you can.

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
0

have you tried a && b && c && ...? Sounds most intuitive to me...

OBu
  • 4,977
  • 3
  • 29
  • 45