Skip to content

Instantly share code, notes, and snippets.

@MineBartekSA
Created Sep 19, 2018
Embed
What would you like to do?
This is a simple bash random number generator, and yet it's overdone!
#!/bin/bash
if ! [ -z $1 ]
then
if [ $1 == "--help" ]
then
echo -e "Number Randomizer aka Rand \e[1mv1.2.1\e[21m"
echo "Usage:"
echo " rand <range> [<repeats> <show only highest>]"
echo " rand <filename> [<repeats> <show only highest>]"
echo "Example:"
echo " rand 10-100 30"
echo " rand 40"
echo " rand 0-3 300 true"
echo " rand list 100"
echo "Deafult: Range 1-10 once"
exit
fi
fi
oh=false
ff=false
rep=1
out=()
min=1
max=10
file=()
if ! [ -z "$1" ]
then
if [ -f $1 ]
then
min=0
max=0
while read p
do
file[$max]=$p
max=$[$max+1]
if [ -z $p ]; then max=$[$max-1]; fi
done < $1
max=$[$max-1]
ff=true
rep=100
elif [[ $1 =~ "-" ]]
then
IFS="-"
inv=$1
ind=0
for a in $inv
do
if ! [ "$a" -eq "$a" ] 2> /dev/null
then
echo "Error: Invalid Range!"
exit
fi
ind=$[$ind+1]
if [ $ind -eq 1 ]
then
min=$a
elif [ $ind -eq 2 ]
then
max=$a
else
echo "Error: Invalid Range!"
exit
fi
done
#echo "Min: $min Max: $max"
elif ! [ "$1" -eq "$1" ] 2> /dev/null
then
echo "Error: Invalid Range!"
exit
else
max=$1
fi
fi
if ! [ -z $2 ]
then
if ! [ "$2" -eq "$2" ] 2> /dev/null
then
echo "Error: Invalid Repete count!"
exit
fi
rep=$2
fi
if ! [ -z $3 ]
then
if [ $3 == "true" ]
then
oh=true
elif [ $3 == "false" ]
then
oh=false
else
echo "Error: Invalid expresion!"
exit
fi
fi
for ((i=1; i<=$rep; i++))
do
t=$[ ($RANDOM % ($max + (1 - $min))) + $min ]
#echo $t
for ((v=$min; v<=$max; v++))
do
if [ $v == $t ]
then
out[$v]=$[${out[$v]}+1]
fi
done
done
if [ $rep -ne 1 ]
then
h=0
hi=0
for ((n=$min; n<=$max; n++))
do
if ! [ -z ${out[$n]} ]
then
if ! $oh; then if $ff; then echo "${file[$n]}: ${out[$n]}"; else echo "$n: ${out[$n]}"; fi; fi
if [ ${out[$n]} -gt $h ]
then
h=${out[$n]}
hi=$n
fi
fi
done
for ((n=$min; n<=$max; n++))
do
if [[ $h -eq ${out[$n]} && $n -ne $hi ]]
then
shi=$n
fi
done
if ! $oh; then echo "-----"; fi
if $ff
then
if [ -z $shi ]
then
echo "Highest: ${file[$hi]}"
else
echo "Highest: ${file[$hi]} and ${file[$shi]}"
fi
else
if [ -z $shi ]
then
echo "Highest: $hi"
else
echo "Highest: $hi and $shi"
fi
fi
else
for n in ${!out[@]}; do echo $n; done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment