bash - 参数太多 Shell 脚本 if 检查

标签 bash shell

我正在尝试检查当天是星期日还是星期五,以及时间是否晚于20
如果是这样,那么我想做点什么;如果没有,我想做点别的事情。
我正在使用 /bin/sh

这给了我以下错误:

Too many arguments.

为什么?

   day_of_week=$(date -d $given_date +%u )
   hour_of_day=${ST_job:0:2}
   if [ [ $day_of_week -eq 7 ] || [ [ $day_of_week -eq 5 ] && [ $hour_of_day -gt 20 ] ] ] ; then
       something
   else
       something else
   fi

谢谢

最佳答案

您可能认为“[”只是一个分组,并且您可以有不同的任意嵌套。

事实并非如此。

“[”是 shell“test”命令的别名...并且您需要正确匹配它们:

https://www.shellscript.sh/test.html

Test is used by virtually every shell script written. It may not seem that way, because test is not often called directly. test is more frequently called as [. [ is a symbolic link to test, just to make shell programs more readable. It is also normally a shell builtin (which means that the shell itself will interpret [ as meaning test, even if your Unix environment is set up differently):

$ type [
[ is a shell builtin
$ which [
/usr/bin/[
$ ls -l /usr/bin/[
lrwxrwxrwx 1 root root 4 Mar 27 2000 /usr/bin/[ -> test
$ ls -l /usr/bin/test
-rwxr-xr-x 1 root root 35368 Mar 27  2000 /usr/bin/test

在此处查看更多详细信息(以及一些有用的示例):

Advanced Bash-Scripting Guide: 7.4. Nested if/then Condition Tests

关于bash - 参数太多 Shell 脚本 if 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61515485/

相关文章:

regex - 如何在每行的开头添加一个单词而不是在出现 # 时

regex - Bash 计算字符串中的字母,输出总是有点不同

linux - Grep for specified words in .txt 返回不需要的行

linux - 编写多个 sed 命令的更简洁的方法?

regex - 用 sed 替换区域文件中的序列号

bash - 为什么 (*.foo|bar) 会导致错误,而 !(*.foo|bar) 不会?

bash - 在 if 语句中传递参数

linux - 如果屏幕已经在运行,如何检查 If-Statement

bash - 如何检查 bash 脚本是否正在运行并退出

bash - 如何安排每个月的第一个星期天运行