Skip to content

Instantly share code, notes, and snippets.

@qiolol
Created June 15, 2020 13:58
Show Gist options
  • Save qiolol/6a0b51ac7eb7857e12d858a531d1e8ff to your computer and use it in GitHub Desktop.
Save qiolol/6a0b51ac7eb7857e12d858a531d1e8ff to your computer and use it in GitHub Desktop.
Polyhedral dice roller in Bash
#!/usr/bin/env bash
# Roll X dice with Y sides where $1 = "XdY" or "Y" and "X" is implied to be 1
# Inspired by Tippex x3
function roll() {
local re="^([1-9][0-9]*)*([dD]{0,1}([1-9][0-9]*)){0,1}$"
if [[ $1 =~ $re && ! $2 ]] ; then
# Parse input
local dice=1
local sides=0
if [[ ${BASH_REMATCH[1]} && ${BASH_REMATCH[3]} ]] ; then # E.g., "1d12"
dice=${BASH_REMATCH[1]}
sides=${BASH_REMATCH[3]}
elif [[ ${BASH_REMATCH[2]} ]] ; then # E.g., "d12"
sides=${BASH_REMATCH[3]}
else # E.g., "12"
sides=${BASH_REMATCH[1]}
fi
# Roll dice
local total=0
for i in $(seq 1 $dice) ; do
local roll=$(shuf -i 1-$sides -n 1)
total=$((total+roll))
# Print each die if many dice
if [[ $dice > 1 ]] ; then
echo "Die $i: $roll"
fi
done
echo $total
else
echo -n "ERROR! Usage: \"roll X dice with Y sides\" where \$1 = "
echo "\"[Xd]Y\" and X and Y are both greater than zero."
echo "E.g., \"1d12\", \"d12\", and \"12\" are all one 12-sided die."
fi
}
roll $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment