[TynesideLUG] die/dice roller in bash

Ian Bruntlett ian.bruntlett at gmail.com
Sat Dec 30 17:07:37 UTC 2023


Hi,

I was waiting for my washing machine to finish when I decided to play
around with bash. Amongst other, irrelevant exercises, I wrote a die/dice
roller program.

If you're into D&D you might be interested to find out you can specify the
number of sides of the die and the number of times to roll.

Here it is, if you are curious...
#!/usr/bin/env bash
# die-roller. By Ian Bruntlett. 30th December 2023.

# Default options copied from "Learning Modern Linux".
set -o errexit  # Stop the script execution if an error happens.
set -o nounset  # Treat unset variables as an error
# When one part of a pipe fails, the whole pipe should be considered
failed. This helps to avoid silent failures.
set -o pipefail

function roll_die()
{
    local n SIDES
    SIDES=$1
    n=$(( (RANDOM % SIDES) + 1 ))
    echo rolled d"$SIDES" and got $n
}

if [ $# -ne 0 ]  && [ "$1" = "--help"  ]; then
    echo "Usage: $0 number_of_sides number_of_attempts"
    echo Where number_of_sides defaults to 6  and number_of_attempts
defaults to 1
    exit 1
fi

SIDES=6
if [ $# -ge 1  ] ; then
  SIDES=$1;
fi;

ATTEMPTS=1
if [ $# -ge 2  ] ; then
  ATTEMPTS=$2;
fi;


echo "Random number roller d$SIDES sides $ATTEMPTS times"
for (( n=0; n<ATTEMPTS; ++n)); do
  roll_die "$SIDES"
done

# end of script

I used shellcheck a _lot_ to improve the quality of the code. I also
Googled for some things, also.

HTH,


Ian

-- 
-- ACCU - Professionalism in programming - http://www.accu.org
-- My writing - https://sites.google.com/site/ianbruntlett/
-- Free Software page -
https://github.com/ian-bruntlett/TECH-Manuals/blob/main/tm-free-software.md


More information about the Tyneside mailing list