l i n u x - u s e r s - g r o u p - o f - d a v i s
Next Meeting:
July 7: Social gathering
Next Installfest:
Latest News:
Jun. 14: June LUGOD meeting cancelled
Page last updated:
2001 Dec 30 17:03

The following is an archive of a post made to our 'vox-tech mailing list' by one of its subscribers.

Report this post as spam:

(Enter your email address)
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:

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.


LUGOD Group on LinkedIn
Sign up for LUGOD event announcements
Your email address:
LUGOD Group on Facebook
'Like' LUGOD on Facebook:

Hosting provided by:
Sunset Systems
Sunset Systems offers preconfigured Linux systems, remote system administration and custom software development.

LUGOD: Linux Users' Group of Davis
PO Box 2082, Davis, CA 95617
Contact Us

LUGOD is a 501(c)7 non-profit organization
based in Davis, California
and serving the Sacramento area.
"Linux" is a trademark of Linus Torvalds.

Sponsored in part by:
O'Reilly and Associates
For numerous book donations.