$RANDOM

Shell scripting just isn’t my bag. Maybe it’s that I started life with DOS and batch files, or that my first scripts were in csh (not the greatest shell to script with). I just tend to write everything but the most basic things in Perl. Sometimes, though, I just need to fix a shell script. I hate grafting Perl in the middle of a script, mostly because I know damn well you can do whatever you need with the shell.

Every time I have to fix a shell script I end up learning something. That is, provided I can figure out how to ask Google for what I want to know. 🙂

Today I wanted to introduce a random sleep into a script we run on 600 machines from cron, every 10 minutes. This script emails performance data to another server via an intermediate SMTP server. With 600 hosts doing it it’s like our own little DDoS.

So how the heck do you get a random number in bash?

30 seconds of searching in Google: $RANDOM will return a number between 0 and 32768. Cool. If I divide $RANDOM by something like 1000 I’d have a wonderful small sleep.

So how I do math in a shell script?

60 seconds of searching in Google: $(echo “$RANDOM/1000” | bc). bc in the house!

I think tomorrow I’ll troll around in /usr/bin and see what other sorts of cool things are in there. I just think it’s neat that it took me less time to fix the problem than to discover it. I wish it was always that way.

4 thoughts on “$RANDOM”

  1. Back in the day when I was a wee, keen Unix/C programmer (mid 80’s), I’d regularly leaf through the various command and system call manuals just to see what was there.

    However, this year, I was roundly mugged by a BOfH who instead of writing the right SQL to query the hosts database to get the information he wanted, insisted on using the “join” command to produce the report he wanted.

    Erk.

    Anything involving math, job control, talking to any other system really should be done in perl. Or emacs.

Comments are closed.