27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

throw=0<br />

zeroes=0<br />

ones=0<br />

twos=0<br />

threes=0<br />

fours=0<br />

fives=0<br />

sixes=0<br />

# Throw count.<br />

# Must initialize counts to zero.<br />

# since an uninitialized variable is null, not zero.<br />

print_result ()<br />

{<br />

echo<br />

echo "ones = $ones"<br />

echo "twos = $twos"<br />

echo "threes = $threes"<br />

echo "fours = $fours"<br />

echo "fives = $fives"<br />

echo "sixes = $sixes"<br />

echo<br />

}<br />

update_count()<br />

{<br />

case "$1" in<br />

0) let "ones += 1";; # Since die has no "zero", this corresponds to 1.<br />

1) let "twos += 1";; # And this to 2, etc.<br />

2) let "threes += 1";;<br />

3) let "fours += 1";;<br />

4) let "fives += 1";;<br />

5) let "sixes += 1";;<br />

esac<br />

}<br />

echo<br />

while [ "$throw" −lt "$MAXTHROWS" ]<br />

do<br />

let "die1 = RANDOM % $PIPS"<br />

update_count $die1<br />

let "throw += 1"<br />

done<br />

print_result<br />

# The scores should distribute fairly evenly, assuming RANDOM is fairly random.<br />

# With $MAXTHROWS at 600, all should cluster around 100, plus−or−minus 20 or so.<br />

#<br />

# Keep in mind that RANDOM is a pseudorandom generator,<br />

# and not a spectacularly good one at that.<br />

# Exercise (easy):<br />

# −−−−−−−−−−−−−−−<br />

# Rewrite this script to flip a coin 1000 times.<br />

# Choices are "HEADS" or "TAILS".<br />

exit 0<br />

As we have seen in the last example, it is best to "reseed" the RANDOM generator each time it is invoked.<br />

Using the same seed for RANDOM repeats the same series of numbers. (This mirrors the behavior of the<br />

Chapter 9. Variables Revisited 99

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!