#!/bin/bash # rolldice -- parse requested dice to roll and simulate those rolls # examples: d6 = one 6-sided die # 2d12 = two 12-sided dice # d4 3d8 2d20 = a 4-side die, 3 8-sided and 2 20-sided dice rolldie() { dice=$1 dicecount=1 sum=0 # first step, break down arg into MdN if [ -z "$(echo $dice | grep 'd')" ] ; then quantity=1 sides=$dice else quantity=$(echo $dice | cut -dd -f1) if [ -z "$quantity" ] ; then # user specifyed dN not just N quantity=1 fi sides=$(echo $dice | cut -dd -f2) fi echo "" ; echo "rolling $quantity $sides-sided die" # now roll the dice... while [ $dicecount -le $quantity ] ; do roll=$(( ( $RANDOM % $sides ) + 1 )) sum=$(( $sum + $roll )) echo " roll #$dicecount = $roll" dicecount=$(( $dicecount + 1 )) done echo I rolled $dice and it added up to $sum } while [ $# -gt 0 ] ; do rolldie $1 sumtotal=$(( $sumtotal + $sum )) shift done echo "" echo "In total, all of those dice add up to $sumtotal" echo "" exit 0