LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   BASH Script and $RANDOM (https://www.linuxquestions.org/questions/programming-9/bash-script-and-%24random-868619/)

lupusarcanus 03-15-2011 12:09 AM

BASH Script and $RANDOM
 
Inspired by this thread, I wrote a small BASH script just for the hell of it.

Anyway, take a look at it first:
Code:

#! /bin/bash

C="0"
while (true)
do
A="$RANDOM"
B="$RANDOM"
let C++
if [ $A -eq $B ]; then
echo "Incredible! The cosmos have bestowed $A upon you as your lucky number."
echo "Your UNIX system selected the same number twice consecutively from the boundless pool of '/dev/random'. This is a highly improbable feat; you are truly blessed!"
echo
echo
echo "…of course, it took $C attempts to do it. :P"
break
fi
done

Two questions:
  • Is it possible for the script to ever break the loop?
  • Is there anything wrong (syntactically and/or logically) with the script?
Thanks for all help in advance; it is much appreciated even if the script is just for giggles. :p

corp769 03-15-2011 02:21 AM

First of all, I would like to say thanks, as my thread inspired you to do this LOL

But seriously now, I have to run this and time it once I get home to see, if it would ever break, how LONG this would take. Thanks for giving me something to do with my time!

And also, if I think of anything to make it better, I will let you know.

Josh

grail 03-15-2011 02:24 AM

Based on the following:
Quote:

$RANDOM is an internal Bash function (not a constant) that returns a pseudorandom [1] integer in the range 0 - 32767.
Yes to eventually being equal at least after this maximum is reached.

As to:
Quote:

Is there anything wrong (syntactically and/or logically) with the script?
1. Zero indenting which makes it quite difficult to read
2. C is an integer and not a string so quoting would not seem appropriate although it of course causes no error
3. (()) is used by bash for numeric comparisons and arithmetic so the following changes could be made:
Code:

if [ $A -eq $B ]; then

if (( A == B )); then

let C++

((C++))

4. Personally I am not fond of infinite loops so I would probably have an actual test in the while loop.


All times are GMT -5. The time now is 12:20 PM.