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?

4

2 回答 2

3

for循环是这样做的方法;中没有等效all的构造bash

Python 文档显示这些是等效的: http: //docs.python.org/2/library/functions.html#all

请记住,bash它旨在很好地完成一件事(shell 操作),因此如果您发现自己经常需要更高级别的构造,请考虑尽可能选择功能更全面的语言。

于 2013-09-16T23:52:54.113 回答
0

你试过a && b && c && ...吗?对我来说听起来最直观...

于 2013-09-16T23:43:56.733 回答