Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当检查多个语句时,bash中条件语句的最佳实践是什么?_Bash - Fatal编程技术网

当检查多个语句时,bash中条件语句的最佳实践是什么?

当检查多个语句时,bash中条件语句的最佳实践是什么?,bash,Bash,假设您尝试检查变量是否为空,以及是否为以下代码中的其他值: if [ ! -z "$foo" ] && [[ ${foo} != "bar" ]]; then 实现这一点的最佳实践是什么。我见过bash条件语句以多种方式编写,包括以下内容 if [[ ! -z "$foo" && ${foo} != "bar" ]]; then 我知道使用单括号和双括号是有区别的,我更关心的是何时将&&或|放在括号内或括号外。将&&/|放在[]的括号内。外界也可以接受 将&&

假设您尝试检查变量是否为空,以及是否为以下代码中的其他值:

if [ ! -z "$foo" ] && [[ ${foo} != "bar" ]]; then
实现这一点的最佳实践是什么。我见过bash条件语句以多种方式编写,包括以下内容

if [[ ! -z "$foo" && ${foo} != "bar" ]]; then

我知道使用单括号和双括号是有区别的,我更关心的是何时将
&&
|
放在括号内或括号外。

&&
/
|
放在
[]
的括号内。外界也可以接受


&&
/
|
放在
[]
的括号外。里面是不允许的

这是因为
&
根据返回值将普通命令绑定在一起,例如

wget file && echo "Success"
[
,尽管它的名字很有趣,但它是一个常规命令,并且遵守与
wget
echo
相同的规则

[foo | | bar]
是两个命令,
[foo
bar]
,这两个命令都无效


另一方面,
[[…]]
不是一个普通的命令,而是特殊的shell语法。
[[foo | | bar]]
是一个单独的命令,并进行相应的解释。

要完成前面的回答:

if [[ ! -z $foo && $foo != "bar" ]]; then ...
# [[ will execute the two conditions with "and" operator in a single instruction
相当于:

if [[ ! -z $foo -a $foo != "bar" ]]; then ...
# [[ will execute the two conditions with "and" operator in a single instruction
if [[ ! -z $foo ]] && [[ $foo != "bar" ]]; then ...
# second [[ will be executed if the first success ($? = 0)
但不等同于:

if [[ ! -z $foo -a $foo != "bar" ]]; then ...
# [[ will execute the two conditions with "and" operator in a single instruction
if [[ ! -z $foo ]] && [[ $foo != "bar" ]]; then ...
# second [[ will be executed if the first success ($? = 0)
-a
(and)和
-o
(or)将与
测试
[
一起使用

有关详细信息,请参见
人工测试

否则,在这种情况下,不需要使用双引号保护变量,也不需要使用分隔符(
${}


[[
是一个关键字,
[
是一个内置的。请检查bash中的
类型[[
类型[
。@这不仅仅是一个实现优化。
内置的[
有更多选项,
命令[
(在我的系统上)。您只需要一个条件:如果
foo
为空,则它不会等于
bar