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

Diamonds<br />

Hearts<br />

Spades"<br />

Denominations="2<br />

3<br />

4<br />

5<br />

6<br />

7<br />

8<br />

9<br />

10<br />

Jack<br />

Queen<br />

King<br />

Ace"<br />

suite=($Suites)<br />

denomination=($Denominations)<br />

# Read into array variable.<br />

num_suites=${#suite[*]} # Count how many elements.<br />

num_denominations=${#denomination[*]}<br />

echo −n "${denomination[$((RANDOM%num_denominations))]} of "<br />

echo ${suite[$((RANDOM%num_suites))]}<br />

# $bozo sh pick−cards.sh<br />

# Jack of Clubs<br />

# Thank you, "jipe," for pointing out this use of $RANDOM.<br />

exit 0<br />

Jipe points out another set of techniques for generating random numbers within a range.<br />

# Generate random number between 6 and 30.<br />

rnumber=$((RANDOM%25+6))<br />

# Generate random number in the same 6 − 30 range,<br />

#+ but the number must be evenly divisible by 3.<br />

rnumber=$(((RANDOM%30/3+1)*3))<br />

# Exercise: Try to figure out the pattern here.<br />

Just how random is $RANDOM? The best way to test this is to write a script that tracks the distribution of<br />

"random" numbers generated by $RANDOM. Let's roll a $RANDOM die a few times...<br />

Example 9−25. Rolling the die with RANDOM<br />

#!/bin/bash<br />

# How random is RANDOM?<br />

RANDOM=$$<br />

PIPS=6<br />

MAXTHROWS=600<br />

# Reseed the random number generator using script process ID.<br />

# A die has 6 pips.<br />

# Increase this, if you have nothing better to do with your time.<br />

Chapter 9. Variables Revisited 98

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

Saved successfully!

Ooh no, something went wrong!