Thursday, 27 August 2009

Rolling dice in Bash

I often need short random numbers at work. For example, if I'm scheduling a whole bunch of servers to do the same automated tasks and I want them to not run at exactly the same time, I'll use a random number between 1 and 60 to have them run on different minutes. You can do this somewhat easily in bash using the $RANDOM variable and a mod operation like so:

echo $((RANDOM%60))


However, it's a bit long to type and sometimes I need batches of numbers. So I looked around at dice rolling programs but most were too fancy. So I wrote a simple simple script I called "roll" which returns sets of random numbers.

#!/bin/bash

# Roll
# This script returns the values and sum of a set of dice rolls. The first
# arg is optional and gives a number of dice. The second arg is the number
# of sides on the dice. For example "roll 2 6" will give two values from 1
# to 6 and also returns their sum.
#
# (c)2009 Dominic Lepiane

sides=6
dice=1
total=0
c=0

if [ $# = 2 ] ; then
dice=$1
sides=$2
elif [ $# = 1 ] ; then
sides=$1
else
echo "Usage: $0 [# of dice] <# of sides>" >&2
exit -1
fi

#echo "Rolling {$dice}d{$sides}"

while [ $c -lt $dice ] ; do
c=$((c+1))
roll=$((RANDOM%sides + 1))
total=$((total+roll))
echo -n "$roll "
done

if [ $dice -gt 1 ] ; then
echo -n " = $total"
fi

echo ""


So if I want 12 numbers from 1 to 60, it looks like this:

./roll 12 60
21 32 30 38 56 36 27 19 25 34 25 48 = 391


Very handy!

Popular Posts