Linux Blog

Random Numbers in Bash

Filed under: Shell Script Sundays — Owen at 8:00 am on Sunday, February 22, 2015

Going back to last weeks article on running things continuously, part of the use case was generating random numbers.

While using echo $RANDOM works, but it doesn’t work very well for having a minimum and max value. There are techniques to do this, but what I’ve found easier is to use another language of your choice and run that separately using expansion ( $() or “). I’m sure there is a way to do it in Ruby and Python and whatever language but since I’m familiar with PHP, I’ll use that in this example first:

1
2
3
for i in `seq 1 10`; do
echo `php -r 'echo rand(1, 100);'`
done;

This example iterates the loop 10 times, and echo’s a random number between 1 and 100. here is more information on PHP’s random function Note that this does require having php5-cli package installed.

If you don’t have PHP, but have perl you can use:

1
2
3
for i in `seq 1 10`; do
echo `perl 'print rand(100);'`
done;

That’s great and all, but perl uses what looks like floating numbers. To get an int, you have to cast to an int which adds additional typing:

1
2
3
for i in `seq 1 10`; do
echo `perl 'print int(rand(100));'`
done;

To me, this is easier but, if you don’t have PHP, Perl, Ruby, Python or whatever your choice, you could use bash (I always forget how, but here it is for reference:)

echo $[ 1 + $[ RANDOM % 100 ]]

Or if you have complex requirements, you could write a quick binary that does the same thing. Another alternative is to use another shell that you do have access to that happens to have a more robust RNG.





Random Man Pages:
socket
I18N::Collate
QRegion
quiz

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>