Awk|Bash - creating random number.
Home page Ubuntu C++ Hardware HTML i javascript Java Software SQL

Awk|Bash - creating random number.

Added: 2012-03-09

Script language bash is very good tool, with awk it give lot of possibility administrator and user, to more quickly perform operations.

Script give user possibility to create tools for a while or longer time.

Sometimes you need a script that generates a random number in the range. My script in case if not the exist parameters display help. In case of bad parameters script will ended and will be returned exit code. Exit code you can check by command $?, value ten is not exist parameter, exit code twelve, argument is not number.

Bellow example.

Once click select code, double click print code.

#!/bin/bash

function help_(){
         echo "The script generates a random number in the range specified by the inverval number. "
         echo "The script have two parameters: 1 - start interval number, 2 - end interval number."
}


if [ "$1" = "" ]; then
	echo `help_`;
	exit 10
elif [ "$2" = "" ]; then
	echo `help_`;
	exit 10
fi

function isNumber(){
	echo $1 | grep '^[0-9]*$' > NULL
	if [ "$?" -eq "0" ]; then
		echo "1"
	else 
		echo "0"
	fi
}

if [ "`isNumber $1`" = "0" ]; then
	exit 12
fi

if [ "`isNumber $2`" = "0" ]; then
	exit 12
fi


awk -vs=$1 -ve=$2 'BEGIN {
   srand()
   print int(s + rand() * (e-s+1))
}'