l i n u x - u s e r s - g r o u p - o f - d a v i s
L U G O D
 
Next Meeting:
December 2: Social gathering
Next Installfest:
TBD
Latest News:
Nov. 18: Club officer elections
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


  • 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


LinkedIn
LUGOD Group on LinkedIn
Sign up for LUGOD event announcements
Your email address:
facebook
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:
Sunset Systems
Who graciously hosts our website & mailing lists!