LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash random function (https://www.linuxquestions.org/questions/programming-9/bash-random-function-43745/)

NSKL 02-02-2003 09:23 AM

bash random function
 
I want to write a simple bash script that, when executed, will pick a random of 5 colors and start a aterm with that color.

So far i have just defined the vars:
RED="aterm -tint red"
GREEN="aterm -tint green"
and so on for every tint color, you get the point.
Now is there a random function that i can use, that will choose one of the variables and execute it? I know something like this exists in Perl, but is there a easy way in bash?
Thank you.
-NSKL

leed_25 02-02-2003 11:58 AM

from the Bash manpage:

,----
| Shell Variables
| The following variables are set by the shell:
|
| [. . .]
|
| RANDOM Each time this parameter is referenced, a random
| integer between 0 and 32767 is generated. The
| sequence of random numbers may be initialized by
| assigning a value to RANDOM. If RANDOM is unset,
| it loses its special properties, even if it is sub-
| sequently reset.
`----

so, just do this:

$ echo $RANDOM

NSKL 02-02-2003 12:50 PM

Thanks for help, but i never read anything about bash scriping, just looked at some scripts and tried to figure out how it works, which is pretty much like any programming lang, but im still very newbie...
So, i have defined my vars:

RED="aterm -options"
GREEN="aterm -options"
BLUE="aterm -options"
CLEAR="aterm -options"
YELLOW="aterm -options"

now how would i go about using echo $RANDOM to pick one of the 5 vars, and execute it?
Thanks in advance
-NSKL

unSpawn 02-02-2003 01:03 PM

case ${RANDOM:0:1} in
0) RED="aterm -tint red";;
1) GREEN="aterm -tint green";;
# etc etc
esac

*search TLDP for the "Advanced bash Scripting Guide".

NSKL 02-02-2003 01:11 PM

Thank you, i'll invest in a good book too...
-NSKL

leed_25 02-02-2003 01:34 PM

Why not try something along these lines:

Code:

#!/bin/bash

array=(\
        "echo 1" \
        "echo 2" \
        "echo 3" \
        "echo 4" \
        "echo 5")

exec ${array[$((RANDOM %= $((${#array[@]}))))]}

each time you execute the script, a random command from the array
will be executed

leed_25 02-02-2003 01:39 PM

I like unspawn's better. I didn't know about the 0:1 thang.

edit::

the 0:1 thang just selects the first character of the
random number string generated by $RANDOM --I had to
go read about it in the manpage-- whereas the %=
model generates a random number in the range of
posssible array elements. Take yer pick.

The 0:1 model is much simpler. I still like it.



All times are GMT -5. The time now is 05:46 AM.