bash 算术表达式:期望主要:
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30719911/
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
arithmetic expression: expecting primary:
提问by Luis de la Fuente Nieto
I am trying to do a script in shell that sleeps for a random period of time and after this calls a python script. I am doing this:
我正在尝试在 shell 中执行一个脚本,该脚本会随机休眠一段时间,然后调用 python 脚本。我正在这样做:
#!/bin/bash
now="$(date)"
printf "Current date and time %s\n" "$now"
maxdelay=25
delay=$(($RANDOM%maxdelay)) # pick an independent random delay for each of the 20 runs
echo $delay;
(sleep $((delay*60)); /usr/bin/python pythonscript.py) &
But it is failing, this is the result:
但它失败了,这是结果:
Current date and time mar jun 9 00:02:10 CEST 2015
prueba.sh: 7: prueba.sh: arithmetic expression: expecting primary: "%maxdelay"
Yesterday it works perfect but today I don't know why it is failing
昨天它工作得很好,但今天我不知道为什么它失败了
回答by rici
You seem to be running that script using dash
instead of bash
, possibly because you're invoking the script as
您似乎正在使用dash
而不是运行该脚本bash
,可能是因为您正在调用脚本
sh prueba.sh
instead of
代替
# prueba.sh must have exec permissions
# the shebang line is used to select the interpreter
./prueba.sh
or
或者
bash prueba.sh
RANDOM
is a bash extension; in dash
, it is not special and not assigned by default.
RANDOM
是一个 bash 扩展;in dash
,它并不特殊,默认情况下不分配。
In an arithmetic expression, if $var
is used and var
is unassigned, then it is substituted with an empty string, which often creates a syntax error. On the other hand, if you use var
and var
has not been assigned a value, it is assumed to be 0.
在算术表达式中,如果$var
使用var
且未赋值,则将其替换为空字符串,这通常会产生语法错误。另一方面,如果您使用var
和var
尚未分配值,则假定为 0。
Debian and Ubuntu installs typically use dash
for the /bin/sh
default shell interpreter.
Debian 和 Ubuntu 安装通常dash
用于/bin/sh
默认 shell 解释器。
Note that bash
and dash
produce different error messages:
请注意,bash
并dash
产生不同的错误消息:
$ bash -c 'unset foo;bar=25;echo $(($foo*$bar))'
bash: *25: syntax error: operand expected (error token is "*25")
$ dash -c 'unset foo;bar=25;echo $(($foo*$bar))'
dash: 1: arithmetic expression: expecting primary: "*25"