Bash “如果[…]”和“如果[…]”有什么区别;然后……`和`[…]]&&;…`?

Bash “如果[…]”和“如果[…]”有什么区别;然后……`和`[…]]&&;…`?,bash,Bash,if[…]之间的区别是什么;然后…和Bash中的[[…]]和&&&…构造,而不是语法?例如: if [[ -d /etc ]] ; then echo "I see." ; else echo "I don't." ; fi [[ -d /etc ]] && echo "I see." || echo "I don't." 一方能做什么,另一方不能做什么?没有太多区别,但第一个示例仅使用第一个条件。在第二种情况下,有两种情况会影响输出 if [[ -d /etc ]] ; #

if[…]之间的区别是什么;然后…
和Bash中的
[[…]]和&&&…
构造,而不是语法?例如:

if [[ -d /etc ]] ; then echo "I see." ; else echo "I don't." ; fi
[[ -d /etc ]] && echo "I see." || echo "I don't."

一方能做什么,另一方不能做什么?

没有太多区别,但第一个示例仅使用第一个条件。在第二种情况下,有两种情况会影响输出

if [[ -d /etc ]] ; # only condition that matters
 then echo "I see." ;
 else echo "I don't." ; 
fi

[[ -d /etc ]] &&  # condition 1
echo "I see." || # condition 2
echo "I don't."

在本例中,条件2总是可以的,因为echo是一个内置函数,但是如果它是另一个命令,并且失败了,它将触发or子句,这在第一个示例中是不可能的。第一个示例只使用一个条件,第二个依赖于两个条件。

没有太多区别,但第一个示例仅使用第一个条件。在第二种情况下,有两种情况会影响输出

if [[ -d /etc ]] ; # only condition that matters
 then echo "I see." ;
 else echo "I don't." ; 
fi

[[ -d /etc ]] &&  # condition 1
echo "I see." || # condition 2
echo "I don't."

在本例中,条件2总是可以的,因为echo是一个内置函数,但是如果它是另一个命令,并且失败了,它将触发or子句,这在第一个示例中是不可能的。第一个只使用一个条件,第二个依赖于两个条件。

附录-一个相关的旁白是,您可以在格式正确的if/then/elif/else的每个块中放置多个语句,而无需做很多特别的工作(尽管在
if
部分需要一些欺骗)但是三元构造要求您自己创建块

if true && false || oops
then : "this shan't be executed"
     : but I can put several statements anyway
elif true && true || oops
then echo hello
     echo more statements!
else : I could put more statements here too
     : see?
fi
bash: oops: command not found
hello
more statements!
要在一个三元组中创建多个语句块,您需要这样的东西-

true && {
   echo ok
   echo more
   oops!
} || false {
   echo This still has the same logical vulnerability, now made *worse*
   echo oh, woe.
}
ok
more
bash: oops!: command not found
       echo This still has the same logical vulnerability
This still has the same logical vulnerability
       echo oh, woe.
oh, woe.
    }
bash: syntax error near unexpected token `}'
可以稍微清理一下,但这不是重点。

它们是不同的。

附录-这是一个相关的旁白,您可以在格式正确的if/then/elif/else的每个块中放置多个语句,而无需太多特别的努力(尽管在
if
部分需要一些欺骗),但三元结构要求您自己创建块

if true && false || oops
then : "this shan't be executed"
     : but I can put several statements anyway
elif true && true || oops
then echo hello
     echo more statements!
else : I could put more statements here too
     : see?
fi
bash: oops: command not found
hello
more statements!
要在一个三元组中创建多个语句块,您需要这样的东西-

true && {
   echo ok
   echo more
   oops!
} || false {
   echo This still has the same logical vulnerability, now made *worse*
   echo oh, woe.
}
ok
more
bash: oops!: command not found
       echo This still has the same logical vulnerability
This still has the same logical vulnerability
       echo oh, woe.
oh, woe.
    }
bash: syntax error near unexpected token `}'
可以稍微清理一下,但这不是重点。

它们不一样。

从技术上讲,
echo
可能会失败(例如,如果其标准输出被重定向到只读文件);从技术上讲,
echo
可能会失败(例如,如果它的标准输出被重定向到只读文件);这是不常见的。它是…另请看,特别是评论和。它是…另请看,特别是评论和。