什么为在bash条件语句的最佳实践检查多条语句的时候? [英] whats the best practice for conditionals in bash when checking multiple statements?
问题描述
鉴于你尝试检查一个变量是不是空的,而不是其他一些价值在以下code:
Given your trying to check that a variable is not empty and not some other value as in the following code:
if [ ! -z "$foo" ] && [[ ${foo} != "bar" ]]; then
什么是实现这一目标的最佳做法。我见过的bash条件语句写几种方法包括如下...
what is the best practice for accomplishing this. I've seen bash conditionals written several ways including the following...
if [[ ! -z "$foo" && ${foo} != "bar" ]]; then
据我所知,是使用单支架和双的时候,我更关心的是,当把&放有差别;&安培;
或 ||
括号内或缩小。
推荐答案
将&放大器;&安培;
/ ||
为 [[]]
。外面是可以接受的。
Put &&
/||
inside brackets for [[ ]]
. Outside is also accepted.
将&放大器;&安培;
/ ||
括号外的 []
。里面是不允许的。
Put &&
/||
outside brackets for [ ]
. Inside is NOT allowed.
这是由于这一事实,即&放大器;&安培;
根据返回值,例如正常结合在一起的命令
This is due to the fact that &&
binds normal commands together based on return value, e.g.
wget file && echo "Success"
[
,尽管它的有趣的名字,是一个普通的命令,并遵守相同的规则,例如的wget
或回声
。
[
, despite its funny name, is a regular command and obeys the same rules as e.g. wget
or echo
.
[富||巴]
是两个命令, [富
和巴]
,这两者都不是有效的
[ foo || bar ]
is two commands, [ foo
and bar ]
, neither of which are valid.
[[..]]
,另一方面是不是一个正常的命令,但特殊的shell语法。 [富||巴]]
是一个单一的命令,除$ P $据此ptted。
[[ .. ]]
on the other hand is not a normal command but special shell syntax. [[ foo || bar ]]
is a single command, and interpretted accordingly.
这篇关于什么为在bash条件语句的最佳实践检查多条语句的时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!