Re: [vox-tech] bash question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [vox-tech] bash question
On Mon 16 Apr 01, 1:12 PM, Micah Cowan said:
> 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.
bill, here's a MUCH simpler method:
var=2
shift $var
echo $1 <-- $1 now holds the var'th command line argument.
arguments start at 0, so var=0 corresponds to the first argument.
nice short lines. simple.
pete
|