Re: [vox-tech] bash question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [vox-tech] bash question
- Subject: Re: [vox-tech] bash question
- From: Micah Cowan <mMAPSicah@cowanbox.com>
- Date: Mon, 16 Apr 2001 12:54:38 -0700
- References: 200104161951.f3GJp2b19720@sonic.net
On Mon, Apr 16, 2001 at 12:51:02PM -0700, William Kendrick wrote:
> I'm trying to write a simple shell script which takes in a list of
> arguments and then picks one randomly and spits it out.
>
> In otherwords, if you run:
>
> ./random.sh Hello World How Are You
>
> You will sometimes get the word "Hello", sometimes "You", sometimes "How", etc.
>
>
> Picking the random number is pretty simple:
>
>
> PICK=`expr $RANDOM % $#`
>
> (pick an entirely random number, and then MOD it by the number of arguments
> sent to the program, thus getting a number between 0 and num_args - 1)
Bill, the following:
------------------------
#!/bin/bash
declare -a my_array
my_array=("$@")
element_to_print=$(( $RANDOM * ${#my_array[@]} / 32767 ))
echo "${my_array[$element_to_print]}"
------------------------
Works for me. This relies on arrays, so notice that this won't work
on older bash's. There may well be another way to do this that
doesn't rely on arrays, but this works for me.
HTH
Micah
|