Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top