2

I want to get random number within specific range:

random_number=$(( RANDOM % $RANGE ))

this gives me an error

 ")syntax error: invalid arithmetic operator (error token is "

I assume I can't use $RANGE in this expression, but why? How can I rewrite this?

minerals
  • 1,195
  • 4
  • 15
  • 22

2 Answers2

3

Isn't it this:

random_number = $(( $RANDOM % $RANGE ))

$ before RANDOM

If that doesn't work this post:

Suggests:

shuf -i 2000-65000 -n 1

UPDATE
A way to rewrite this is as follows:

 random_number = $(( $RANDOM % some_numeric_value ))
Community
  • 1
  • 1
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
  • 1
    Actually you can omit the `$` within an arithmetic expression. – zakinster Apr 29 '13 at 12:02
  • @minerals I updated with an approach, where you just feed the upper limit you want to mod against, instead of relying on `$Range` let me know if this works for you. Is there a bash fiddle or something equivalent so I can better test? – Woot4Moo Apr 29 '13 at 12:03
2

It looks like your variable RANGE may be polluted by a carriage return or something else.

If you're on Windows, there may be an \r from a misconfiguration of the EOL, you could try this :

random_number = $(( RANDOM % $(tr -d '\r' <<< "$RANGE") ))
zakinster
  • 10,508
  • 1
  • 41
  • 52