bash的逻辑运算符如何工作(或为什么它们在这里不工作)? [英] How do bash's logical operators work (or why don't they work here)?
问题描述
我有以下包装器脚本:
#!/bin/bash
$local_time=`date +%H%M`
if [ $local_time -ge 1430 ] && [ $local_time -le 2230 ] ||
[ $local_time -ge 0300 ] && [ $local_time -le 0400 ]
then
echo 'pass'
else
echo 'skip'
fi
这个想法是创建一个包装器脚本,该脚本在两个不相交的时间间隔之间运行一个脚本.每个要进行或"运算的表达式都可以正确求值,但是,当我对两个表达式进行或"运算时,测试将失败.
The idea being to create a wrapper script that runs a script between two disjoint time intervals. Each of the expressions being OR'd is evaluated correctly, however, when I OR both expressions, the test fails.
我该如何解决?
推荐答案
您有两个问题
- 分配变量时,不要在变量前加上
$
前缀,只有在扩展变量时才使用 - 您需要使用括号
( )
强制执行运算符优先级
- You don't prefix your variables with a
$
when you assign to them, only when you expand them - You need to enforce operator precedence with parens
( )
此外,由于您已经在使用bash
,因此最好将其更好的语法与(( ))
构造一起使用,该构造允许您使用比较运算符< > == !=
,并且可以使用$()
代替命令反引号/刻痕
Also, since you're already using bash
, might as well use its better syntax with the (( ))
construct that allows you to use the comparison operators < > == !=
and you can use $()
for command substitution instead of the backticks/gravemarks
#!/bin/bash
local_time=$(( 10#$( date +'%H%M' ) ))
if (( ( local_time >= 1430 && local_time <= 2230 ) ||
( local_time >= 10#0300 && local_time <= 10#0400 ) ))
then
echo 'pass'
else
echo 'skip'
fi
以零开头的数字被解释为八进制.
同样,任何以0开头且包含8或9的数字都会显示错误.
前缀(10#)可以解决该问题.
Numbers that start with a zero are interpreted as octal.
Also, any number that start with 0 and contains an 8 or 9 will print an error.
Prefixing (10#) solves that.
这篇关于bash的逻辑运算符如何工作(或为什么它们在这里不工作)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!