Operating System - HP-UX
1828161 Members
2544 Online
109975 Solutions
New Discussion

Random Variable at Shell Script

 
Ricardo Bassoi
Regular Advisor

Random Variable at Shell Script


Hi All,

I need to do the following:

var1=;
echo $var1 > file.txt
sleep 30;
var2=cat file.txt
If var1 = var 2 the

....

The problem is : How to create a random variable using shell only ( bash, korn )

If you never try, never will work
6 REPLIES 6
Cheryl Griffin
Honored Contributor

Re: Random Variable at Shell Script

Try random (3M).

# man random
DESCRIPTION
The random() and srandom() functions are random-number generators that have virtually the same calling sequence and initialization properties as the rand() and srand() functions, but produce sequences that are more random
Cheryl
"Downtime is a Crime."
Cheryl Griffin
Honored Contributor

Re: Random Variable at Shell Script

http://forums.itrc.hp.com/cm/QuestionAnswer/1,,0x67657e990647d4118fee0090279cd0f9,00.html is a example.

Search the forums and you will find more.

Search from the left, enter random in the search box and click the option for Community Forum.

Cheryl
"Downtime is a Crime."
Ricardo Bassoi
Regular Advisor

Re: Random Variable at Shell Script

Hi All,

Is there a way to run this random cmd using only shell script ? ( not C or PERL )

Regards
If you never try, never will work
Hai Nguyen_1
Honored Contributor

Re: Random Variable at Shell Script

Ricardo,

There is actually an environment variable named RANDOM which suits your need.

Try several of these to see for yourself
# echo $RANDOM
# echo $RANDOM # diff. output
# ...

Hai
Nick Wickens
Respected Contributor

Re: Random Variable at Shell Script

Heres an example of using random -

RANDOM=$(date +%S)
MESS=$((RANDOM % 5))
case $MESS in
1) echo "Random number 1 generated";;
2) echo "Random number 2 generated";;
3) echo "Random number 3 generated";;
4) echo "Random number 4 generated";;
5) echo "Random number 5 generated";;
esac

The first "variable" RANDOM sets the "seed" (randomness if you like) based on the current date. The variable MESS is then chosen at random between 1 & 5.

Hats ? We don't need no stinkin' hats !!
Nick Wickens
Respected Contributor

Re: Random Variable at Shell Script

Opps Sorry - Actually the example I gave generates a RANDOM number between 0 and 5 !!
Hats ? We don't need no stinkin' hats !!