SHELL - 在IF声明中操作

问题描述 投票:2回答:2

假设这些功能:

return_0() {
   return 0
}

return_1() {
   return 1
}

然后是以下代码:

if return_0; then
   echo "we're in" # this will be displayed
fi

if return_1; then
   echo "we aren't" # this won't be displayed
fi

if return_0 -a return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

为什么我要进入最后一个ifstatement?我们不应该与那些01不符合条件吗?

bash shell if-statement ksh
2个回答
4
投票

-atest命令的选项之一(也由[[[实施)。所以你不能单独使用-a。您可能想要使用&&,它是AND列表的控制运算符标记。

if return_0 && return_1; then ...

你可以使用-a告诉test“和”两个不同的test表达式,如

if test -r /file -a -x /file; then
    echo 'file is readable and executable'
fi

但这相当于

if [ -r /file -a -x /file ]; then ...

这可能更具可读性,因为括号使表达式的测试部分更清晰。

有关...的更多信息,请参阅Bash参考手册。


4
投票

当你执行

if return_0 -a return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

你执行行return_0 -a return_1。这实际上意味着你将-areturn_1作为return_0的参数传递。如果你想要一个和操作,你应该使用&&语法。

if return_0 && return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

理解这一点的有用信息是:

AND和OR列表分别是由&&||控制运算符分隔的一个或多个管道的序列。 AND和OR列表以左关联性执行。 AND列表具有表单

command1 && command2

当且仅当command2返回退出状态为零时才执行command1

OR列表具有表单

command1 || command2

当且仅当command2返回非零退出状态时才执行command1。 AND和OR列表的返回状态是列表中执行的最后一个命令的退出状态。

© www.soinside.com 2019 - 2024. All rights reserved.