To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970. The range of returned values is 0 to 32767.
This will return a number between 1 and 100:
NUMBER=$[ ( $RANDOM % 100 ) + 1 ]
Here is a function to dynamically imitate a die:
#!/bin/bash
#
# Simple script to generate a random number
#
# written by Dallas Vogels
function roll_die() {
# capture parameter
declare -i DIE_SIDES=$1
# check for die sides
if [ ! $DIE_SIDES -gt 0 ]; then
# default to 6
DIE_SIDES=6
fi
# echo to screen
echo $[ ( $RANDOM % $DIE_SIDES ) + 1 ]
}
roll_die 10 # returns 1 to 10
roll_die 2 # returns 1 or 2
Comments
stop the UUOC; `od' takes a
stop the UUOC; `od' takes a file as input, so give it the name of the file instead of piping output from `cat' to `od.'
od -N1 -An -i /dev/urandom
Simplification
echo $((`cat /dev/urandom|od -N1 -An -i` % $max)) gives figure from 0 to $max
Random number shell generator
I think the better way is to use /dev/urandom for this. Read random bits from the file. You can obtain large range. $RANDOM has only 0-32767. E.g.
cat /dev/urandom|od -N4 -An -i
See http://94.228.168.188/en/articles/article_03.html for details.auto num generation
Hie. i am having a serious problem and need a solution soon. How do i auto generate a number in linux scripting?
The script, as shown above,
The script, as shown above, will generate a random number...
thanks alot!
thanks alot!
Script to return a random number between two bounds:
Just to extend your first script a little:
newrand=$[ ( $RANDOM % ( $[ $highest - $lowest ] + 1 ) ) + $lowest ]
Nice one. Thanks!
Nice one. Thanks!
Post new comment