Chirality
Chirality

Reputation: 745

Bash Random Variables = Not so random?

I wanted to generate a random decimal that was rounded to the 10ths place between .1 and 1.

I did this with the command

`echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`

Now if you set it as a variable, say

var=`echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`

and have your script echo var like so,

#!/bin/bash
var=`echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`
echo $var
echo $var
echo $var

It repeats the same decimal, say .4, but if you

#!/bin/bash
echo `echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`
echo `echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`
echo `echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`

It will give you three random numbers using the same command as

$var=`echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`

Why does Bash not generate three new numbers if given the same command but as a variable?

Upvotes: 1

Views: 319

Answers (2)

Slizzered
Slizzered

Reputation: 899

It is because

var=`echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`

executes the echo command and stores its output into a variable. The command itself is only evaluated once by the bash interpreter.

If you want a compact way to generate a random number, I suggest using a function:

#!/bin/bash
myRandom(){
    echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l
}

echo $(myRandom)
echo $(myRandom)
echo $(myRandom)

Upvotes: 2

John1024
John1024

Reputation: 113834

The following command sets a value for var:

var=`echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l`

Once the value is set, it does not change. Thus, however many times you view it, it will be the same:

echo $var
echo $var
echo $var

The only way to get a new value is for bash to evaluate RANDOM again.

Using a function instead

You might prefer a function that would return a different random variable with each invocation:

$ var() { echo "scale=1; $(( ( RANDOM % 10 ) + 1 ))/10" | bc -l; }
$ var
.3
$ var
.4
$ var
1.0
$ var
.4

Upvotes: 4

Related Questions