My today's goal was to further practice POSIX shell scripting.
So, I decided to write the following POSIX shell script for generating pseudo-random numbers.
Any and all reviews would be appreciated.
#!/bin/sh
bold=$(tput bold)
red=$(tput setaf 1)
nocolor=$(tput sgr0)
bold_red="${bold}${red}"
print_error_and_exit()
{
# check if exactly two arguments have been passed
if [ "$#" -ne 2 ]
then
print_error_and_exit "print_error_and_exit(): There have not been passed two arguments!" 2
fi
# check if the second argument is a number
if ! is_this_a_number "$2"
then
print_error_and_exit "print_error_and_exit(): The argument #2 is not a number!" 5
fi
echo "${bold_red}$1 Exit code = $2.${nocolor}" 1>&2
exit "$2"
}
is_this_a_number()
{
# check if exactly one argument has been passed
if [ "$#" -ne 1 ]
then
print_error_and_exit "is_this_a_number(): There has not been passed exactly one argument!" 2
fi
# check if the argument is an integer number
if [ "$1" -eq "$1" ] 2> /dev/null
then
return 0
else
return 1
fi
}
random_number()
{
# check if exactly two arguments have been passed
if [ "$#" -ne 2 ]
then
print_error_and_exit "random_number(): There have not been passed exactly two arguments!" 3
fi
# check if the first argument is a number
if ! is_this_a_number "$1"
then
print_error_and_exit "random_number(): The argument #1 is not a number!" 4
fi
# check if the second argument is a number
if ! is_this_a_number "$2"
then
print_error_and_exit "random_number(): The argument #2 is not a number!" 5
fi
# min is inclusive
range_min="$1"
# max is inclusive too
range_max="$2"
# RANDOM is not POSIX-available,
# so we can use shuf for instance
shuf -i "$range_min"-"$range_max" -n 1
}
# temporary testing loop
i=1
while [ "$i" -lt 10 ]
do
random_number 1 9
i=$((i + 1))
done