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

# Rewrite this script using arrays, rather than indirect variable referencing.<br />

# Which method is more straightforward and intuitive?<br />

# Notes:<br />

# −−−−−<br />

# Shell scripts are inappropriate for anything except the most simple<br />

#+ database applications, and even then it involves workarounds and kludges.<br />

# Much better is to use a language with native support for data structures,<br />

#+ such as C++ or Java (or even Perl).<br />

exit 0<br />

Example 35−4. Using arrays and other miscellaneous trickery to deal four random hands from a deck<br />

of cards<br />

#!/bin/bash<br />

# May need to be invoked with #!/bin/bash2 on older machines.<br />

# Cards:<br />

# deals four random hands from a deck of cards.<br />

UNPICKED=0<br />

PICKED=1<br />

DUPE_CARD=99<br />

LOWER_LIMIT=0<br />

UPPER_LIMIT=51<br />

CARDS_IN_SUIT=13<br />

CARDS=52<br />

declare −a Deck<br />

declare −a Suits<br />

declare −a Cards<br />

# It would have been easier and more intuitive<br />

# with a single, 3−dimensional array.<br />

# Perhaps a future version of Bash will support multidimensional arrays.<br />

initialize_Deck ()<br />

{<br />

i=$LOWER_LIMIT<br />

until [ "$i" −gt $UPPER_LIMIT ]<br />

do<br />

Deck[i]=$UNPICKED # Set each card of "Deck" as unpicked.<br />

let "i += 1"<br />

done<br />

echo<br />

}<br />

initialize_Suits ()<br />

{<br />

Suits[0]=C #Clubs<br />

Suits[1]=D #Diamonds<br />

Suits[2]=H #Hearts<br />

Suits[3]=S #Spades<br />

}<br />

initialize_Cards ()<br />

Chapter 35. Bash, version 2 357

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

Saved successfully!

Ooh no, something went wrong!