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...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

done<br />

echo "Random number between $FLOOR and $RANGE −−− $number"<br />

echo<br />

# Generate binary choice, that is, "true" or "false" value.<br />

BINARY=2<br />

number=$RANDOM<br />

T=1<br />

let "number %= $BINARY"<br />

# let "number >>= 14" gives a better random distribution<br />

# (right shifts out everything except last binary digit).<br />

if [ "$number" −eq $T ]<br />

then<br />

echo "TRUE"<br />

else<br />

echo "FALSE"<br />

fi<br />

echo<br />

# May generate toss of the dice.<br />

SPOTS=7 # Modulo 7 gives range 0 − 6.<br />

DICE=2<br />

ZERO=0<br />

die1=0<br />

die2=0<br />

# Tosses each die separately, and so gives correct odds.<br />

while [ "$die1" −eq $ZERO ] # Can't have a zero come up.<br />

do<br />

let "die1 = $RANDOM % $SPOTS" # Roll first one.<br />

done<br />

while [ "$die2" −eq $ZERO ]<br />

do<br />

let "die2 = $RANDOM % $SPOTS" # Roll second one.<br />

done<br />

let "throw = $die1 + $die2"<br />

echo "Throw of the dice = $throw"<br />

echo<br />

exit 0<br />

Example 9−24. Picking a random card from a deck<br />

#!/bin/bash<br />

# pick−card.sh<br />

# This is an example of choosing a random element of an array.<br />

# Pick a card, any card.<br />

Suites="Clubs<br />

Chapter 9. Variables Revisited 97

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

Saved successfully!

Ooh no, something went wrong!