lundi 20 avril 2015

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?




Aucun commentaire:

Enregistrer un commentaire