Home Forums HCL Reviews Tutorials Articles Register Search Today's Posts Mark Forums Read
 LinuxQuestions.org Shell scripting - Random numbers within a range
 Linux - Newbie This Linux forum is for members that are new to Linux. Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices

 10-09-2005, 06:17 PM #1 felixc Member   Registered: Jul 2005 Location: Canada Distribution: Ubuntu, Debian Posts: 94 Rep: Shell scripting - Random numbers within a range Hello everyone, I am trying to write a small script that will open an aterm window with a random background colour. My idea was to generate a random number between 0 and 4, and then use cases to select which parameters to pass to aterm. In pseudocode: select a random number from 0 to 4 if it's 0: aterm -tr -tint Green if it's 1: aterm -tr -tint Cyan if it's 2: aterm -tr -tint Red if it's 3: aterm -tr -tint NavyBlue if it's 4: aterm -tr -tint Yellow (I know this isn't extremely useful/necessary, but I'm just using this to learn some basics of shell scripting) My problem lies in selecting the random number. Bash's \$RANDOM supposedly gives me values up to 32767. My idea was then to divide the received value by 32767, and then multiply by 4. This, however, only gives me zeroes. Any ideas? Is it because bash is rounding off too soon and all my decimals become 0? If so, how can I get around that? Or is there a better way than \$RANDOM? Thanks, -Felix
 10-09-2005, 06:26 PM #2 zhangmaike Member   Registered: Oct 2004 Distribution: Slackware Posts: 376 Rep: Math in bash is done with integers. It's not just rounding your decimals, there are no decimals. Dividing a number that is from 0 - 32767 by 32767 will give you 0 except for one case: 32767 / 32767. And, of course, 0 * 4 = 0. What you want to do is multiply FIRST, divide LATER. So... intead of: Code: `\$((\$RANDOM/32767*4))` do Code: `\$((\$RANDOM*4/32767))` and that would give you a number between 0 and 3 inclusive, not between 1 and 4 inclusive. The BEST way, by far, would be to use the modulus operator (%) rather than multiplying and dividing... Code: `\$((\$RANDOM%4))` which will give you a number between 0 and 3 inclusive in one math operation instead of two. 1 members found this post helpful.
 10-09-2005, 06:41 PM #3 felixc Member   Registered: Jul 2005 Location: Canada Distribution: Ubuntu, Debian Posts: 94 Original Poster Rep: Thanks! I'll have to think for a little about why the modulo operation works that way, but for now all that matters is that it does, and so does my script (like a charm). Thanks a ton. -Felix PS - I got the modulo part too now, for some reason I'd forgotten basic math. Last edited by felixc; 10-09-2005 at 07:11 PM.