arithmetic expression: expecting primary:

18,427

You seem to be running that script using dash instead of bash, possibly because you're invoking the script as

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.

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.

Debian and Ubuntu installs typically use dash for the /bin/sh default shell interpreter.

Note that bash and dash produce different error messages:

$ 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"
Share:
18,427
Luis de la Fuente Nieto
Author by

Luis de la Fuente Nieto

Updated on December 29, 2022

Comments

  • Luis de la Fuente Nieto
    Luis de la Fuente Nieto over 1 year

    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:

    #!/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