Linux 多个 -a 大于/小于 break bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8791231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:59:47  来源:igfitidea点击:

Multiple -a with greater than / less than break bash script

linuxbashubuntucomparison-operators

提问by Calvin Froedge

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 "&&").

我写了一个 bash 脚本,它只在工作时间执行 curl 调用。出于某种原因,当我添加“-a”运算符时,每小时比较失败(并且由于某种原因,我的 bash 无法识别“&&”)。

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?

我的语法错误还是我的 bash 有问题?

采纳答案by Costi Ciudatu

You cannot use <and >in bash scripts as such. Use -ltand -gtfor that:

您不能在 bash 脚本中使用<>。为此使用-lt-gt

if [ $HOUR -gt 7 -a $HOUR -lt 17 ]

<and >are used by the shell to perform redirection of stdin or stdout.

<并且>被 shell 用来执行 stdin 或 stdout 的重定向。

The comparison that you say is working is actually creating a file named 7in the current directory.

您所说的比较有效实际上是创建一个7在当前目录中命名的文件。

As for &&, that also has a special meaning for the shell and is used for creating an "AND list" of commands.

至于&&,这对 shell 也有特殊含义,用于创建命令的“AND 列表”。

The best documentation for all these: man bash(and man testfor details on comparison operators)

所有这些的最佳文档:(man bash以及man test有关比较运算符的详细信息)

回答by Simon Richter

I suggest you use quotes around variable references and "standard" operators:

我建议您在变量引用和“标准”运算符周围使用引号:

if [ "$HOUR" -gt 7 -a "$HOUR" -lt 17 ]; ...; fi

回答by dogbane

Try using [[instead, because it is safer and has more features. Also use -gtand -ltfor numeric comparison.

尝试[[改用,因为它更安全且功能更多。还可以使用-gt-lt进行数值比较。

if [[ $HOUR -gt 7 && $HOUR -lt 17 ]]
then
    # do something
fi 

回答by jordanm

There are a few answers here but none of them recommend actual numerical context.

这里有一些答案,但没有一个推荐实际的数字上下文。

Here is how to do it in bash:

以下是如何在 bash 中执行此操作:

if (( hour > 7 && hour < 17 )); then
   ...
fi

Note that "$" is not needed to expand variables in numerical context.

请注意,在数字上下文中扩展变量不需要“$”。