大于/小于的多个 -a 中断 bash 脚本
我编写了一个 bash 脚本,仅在工作时间执行curl 调用。由于某种原因,当我添加“-a”运算符时,每小时比较失败(并且由于某种原因,我的 bash 无法识别“&&”)。
虽然脚本要大得多,但这是相关的部分:
HOUR=`date +%k`
if [ $HOUR > 7 -a $HOUR < 17 ];
then
//do sync
fi
脚本给了我错误:
./tracksync: (last line): Cannot open (line number): No such file
但是,这种比较不会失败:
if [ $DAY != "SUNDAY" -a $HOUR > 7 ];
then
//do sync
fi
是我的语法错误还是这是我的 bash 的问题?
I wrote a bash script that performs a curl call only during business hours. For some reason, the hourly comparison fails when I add an "-a" operator (and for some reason my bash does not recognize "&&").
Though the script is much larger, here is the relevant piece:
HOUR=`date +%k`
if [ $HOUR > 7 -a $HOUR < 17 ];
then
//do sync
fi
The script gives me the error:
./tracksync: (last line): Cannot open (line number): No such file
However, this comparison does not fail:
if [ $DAY != "SUNDAY" -a $HOUR > 7 ];
then
//do sync
fi
Is my syntax wrong or is this a problem with my bash?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能在 bash 脚本中使用
<
和>
。使用-lt
和-gt
来实现:<
和>
由 shell 使用来执行重定向标准输入或标准输出。您所说的有效比较实际上是在当前目录中创建一个名为
7
的文件。至于
&&
,它对于 shell 也有特殊的含义,用于创建命令的“AND 列表”。所有这些的最佳文档:
man bash
(以及man test
有关比较运算符的详细信息)You cannot use
<
and>
in bash scripts as such. Use-lt
and-gt
for that:<
and>
are used by the shell to perform redirection of stdin or stdout.The comparison that you say is working is actually creating a file named
7
in the current directory.As for
&&
, that also has a special meaning for the shell and is used for creating an "AND list" of commands.The best documentation for all these:
man bash
(andman test
for details on comparison operators)这里有一些答案,但它们都没有推荐实际的数字背景。
以下是在 bash 中执行此操作的方法:
请注意,不需要“$”来扩展数字上下文中的变量。
There are a few answers here but none of them recommend actual numerical context.
Here is how to do it in bash:
Note that "$" is not needed to expand variables in numerical context.
我建议您在变量引用和“标准”运算符周围使用引号:
I suggest you use quotes around variable references and "standard" operators:
尝试使用
[[
代替,因为它更安全并且具有更多功能。还可以使用-gt
和-lt
进行数字比较。Try using
[[
instead, because it is safer and has more features. Also use-gt
and-lt
for numeric comparison.