Wednesday, February 10, 2016

Shell specifically bash, how to generate random number between 1 to 4

I've had an assignment of which I thought I should be doing, which was to randomly pick four servers at a time, to pick either one of them and appropriately run script on the selected server. Server hostname format ends with a number between 1 to 4.

i=$(echo $(( ($RANDOM % 4 ) + 1)))
hostname=y3xa10${i}
echo $hostname

To try it out on a bash shell, what I got was basically:

# i=$(echo $(( ($RANDOM % 4 ) + 1))); echo y3xa10${i}
y3xa104
# i=$(echo $(( ($RANDOM % 4 ) + 1))); echo y3xa10${i}
y3xa102
# i=$(echo $(( ($RANDOM % 4 ) + 1))); echo y3xa10${i}
y3xa104
# i=$(echo $(( ($RANDOM % 4 ) + 1))); echo y3xa10${i}
y3xa102
# i=$(echo $(( ($RANDOM % 4 ) + 1))); echo y3xa10${i}
y3xa101
# i=$(echo $(( ($RANDOM % 4 ) + 1))); echo y3xa10${i}
y3xa104
# i=$(echo $(( ($RANDOM % 4 ) + 1))); echo y3xa10${i}
y3xa103
# i=$(echo $(( ($RANDOM % 4 ) + 1))); echo y3xa10${i}
y3xa102

I think this suits my requirement pretty much.