[英]If statement 3 conditions Bash
I want to do an if statement with three conditions that have to be satisfied at the same time. 我想用三个必须同时满足的条件来做一个if语句。 I am using Ubuntu Bash for Windows and the values $c1, $c2 and $c3 are non-integer (decimal negative numbers).
我在Windows下使用Ubuntu Bash,值$ c1,$ c2和$ c3是非整数(十进制负数)。
if [ (( $(echo "$c1 < 0" | bc -l) )) ] && [ (( $(echo "$c2 < 0" | bc -l) )) ] && [ (( $(echo "$c3 < 0" | bc -l) )) ];
then
>&2 echo -e " ++ Constraints OK"
else
>&2 echo -e " ++ Constraints WRONG"
fi
However, I get the following syntax error in the if line: syntax error near unexpected token `('
但是,我在if行中收到以下语法错误:
syntax error near unexpected token `('
If I just put one condition: 如果我只提出一个条件:
if (( $(echo "$c1 < 0" | bc -l) ));
it works, but when I add the three of them as AND ( &&
), I get the error. 它可以工作,但是当我将其中三个添加为AND(
&&
)时,出现了错误。 Can anyone help me? 谁能帮我?
Considerably more efficient (assuming you know your values are numbers, and only need to check whether they're all negative) would be: 效率要高得多(假设您知道您的值是数字,并且只需要检查它们是否均为负数)将是:
if [[ $c1 = -* ]] && [[ $c2 = -* ]] && [[ $c3 = -* ]]; then
>&2 echo " ++ Constraints OK"
else
>&2 echo " ++ Constraints WRONG"
fi
If you want to be more specific about the permissible formats (f/e, allowing leading spaces), a regex is another option, which similarly can be implemented more efficiently than spawning a series of subshells invoking bc
: 如果您想更详细地说明允许的格式(f / e,允许前导空格),则正则表达式是另一种选择,与产生一系列调用
bc
的子shell相比,可以更有效地实现它:
nnum_re='^[[:space:]]*-([[:digit:]]*[.][[:digit:]]+|[[:digit:]]+)$'
if [[ $c1 =~ $nnum_re ]] && [[ $c2 =~ $nnum_re ]] && [[ $c3 =~ $nnum_re ]]; then
>&2 echo " ++ Constraints OK"
else
>&2 echo " ++ Constraints WRONG"
fi
First, pass the relational AND operators into bc
to get rid of some punctuation (also only invokes bc
once): 首先,将关系AND运算符传递到
bc
以消除一些标点符号(也仅调用一次bc
):
if (( $(echo "$c1 < 0 && $c2 < 0 && $c3 < 0" | bc -l) == 1 ))
then
>&2 echo -e " ++ Constraints OK"
else
>&2 echo -e " ++ Constraints WRONG"
fi
Although if it were me, I would create a shell function returning a "true" exit status if bc evaluates the result of an expression to non-zero. 虽然是我,但如果bc将表达式的结果计算为非零,我将创建一个返回“ true”退出状态的shell函数。 Then you can hide most of the ugly punctuation in one place separated from your main logic:
然后,您可以将大多数丑陋的标点符号隐藏在与主要逻辑分开的一个地方:
function bc_true() {
(( $(echo "$@" | bc -l) != 0 ))
}
And write a (IMO) cleaner shell expression: 并编写一个(IMO)清洁程序外壳表达式:
if bc_true "$c1 < 0 && $c2 < 0 && $c3 < 0"
then
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.