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

为君一笑 提交于 2019-12-01 18:49:36

You cannot use < and > in bash scripts as such. Use -lt and -gt for that:

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

< 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 (and man test for details on comparison operators)

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

Here is how to do it in bash:

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

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

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

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

Try using [[ instead, because it is safer and has more features. Also use -gt and -lt for numeric comparison.

if [[ $HOUR -gt 7 && $HOUR -lt 17 ]]
then
    # do something
fi 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!