Bash 脚本错误:[: 丢失]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16138841/
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-09-18 05:14:34  来源:igfitidea点击:

Bash Script error: [: missing ]

bashscripting

提问by Shafiq Mustapa

#!/bin/bash
if [ `date +%u` -lt 6 && `date +%H` == '19' ] ; then
   echo 'Sorry, you cannot run this program today.'
else
   echo 'yes, you can run today'
fi

The script above is to run a program on weekdays and every 7PM. I have check the spaces and it still return error : date.sh: 2: [: missing ]

上面的脚本是在工作日和每晚 7 点运行一个程序。我检查了空格,它仍然返回错误:date.sh: 2: [: missing ]

回答by hek2mgl

Change it to:

将其更改为:

#!/bin/bash
if [ `date +%u` -lt 6  ] && [ `date +%H` == '19' ] ; then
   echo 'Sorry, you cannot run this program today.'
else
   echo 'yes, you can run today'
fi

Note that the [is just a shorthand for the testcommand and ]the last argument to it. The &&operator is used like in any other command line, for example cd /home && ls

请注意,这[只是test命令及其]最后一个参数的简写。的&&运算符用于像任何其他命令行,例如cd /home && ls

回答by Cairnarvon

There are two problems with your code.

您的代码有两个问题。

The first is a simple typo: date %Hshould be date +%H.

第一个是一个简单的错字:date %H应该是date +%H

The second is the cause of the error you're seeing: &&isn't the right operator to use. It separates commands, whereas your ifcondition should really be a single one; bash looks for ] at the end of [ `date +%u` -lt 6, doesn't find it, and errors out. You want to use -ainstead.

第二个是您所看到的错误的原因:&&使用的运算符不正确。它分隔命令,而您的if条件实际上应该是一个;bash 在 末尾查找 ] [ `date +%u` -lt 6,没有找到,并出错。你想-a改用。