How to generate a random number in a range which can be positive or negative, by dev/urandom by bash?

Solution 1:

The simplest, cleanest way I can think of is what you already have in your question:

min=-100; max=1; rnd_count=$(( RANDOM % ( $max - $min + 1 ) + $min )); echo $rnd_count

You can easily convert that into a function:

getRand(){
    min="${1:-1}"   ## min is the first parameter, or 1 if no parameter is given           
    max="${2:-100}" ## max is the second parameter, or 100 if no parameter is given
    rnd_count=$((RANDOM % ( $max - $min + 1 ) + $min )); ## get a random value using /dev/urandom
    echo "$rnd_count"
}

If you either paste those lines into your terminal or add them to your ~/.bashrc file and open a new terminal, you can now do:

$ getRand -5 5
-3

That gives a random number between -5 and 5.