LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Shell scripting - Random numbers within a range (https://www.linuxquestions.org/questions/linux-newbie-8/shell-scripting-random-numbers-within-a-range-371322/)

felixc 10-09-2005 05:17 PM

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

zhangmaike 10-09-2005 05:26 PM

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.

felixc 10-09-2005 05:41 PM

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.


All times are GMT -5. The time now is 04:36 PM.