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

# main() {<br />

# Initialize variables.<br />

shots=0<br />

splashes=0<br />

thuds=0<br />

Pi=0<br />

while [ "$shots" −lt "$MAXSHOTS" ]<br />

do<br />

# Main loop.<br />

xCoord=$(get_random)<br />

# Get random X and Y coords.<br />

yCoord=$(get_random)<br />

hypotenuse $xCoord $yCoord # Hypotenuse of right−triangle =<br />

#+ distance.<br />

((shots++))<br />

printf "#%4d " $shots<br />

printf "Xc = %4d " $xCoord<br />

printf "Yc = %4d " $yCoord<br />

printf "Distance = %5d " $distance<br />

# Distance from center<br />

#+ of lake.<br />

if [ "$distance" −le "$DIMENSION" ]<br />

then<br />

echo −n "SPLASH! "<br />

((splashes++))<br />

else<br />

echo −n "THUD! "<br />

((thuds++))<br />

fi<br />

Pi=$(echo "scale=9; $PMULTIPLIER*$splashes/$shots" | bc)<br />

# Multiply ratio by 4.0.<br />

echo −n "PI ~ $Pi"<br />

echo<br />

done<br />

echo<br />

echo "After $shots shots, PI looks like approximately $Pi."<br />

# Tends to run a bit high...<br />

# Probably due to round−off error and imperfect randomness of $RANDOM.<br />

echo<br />

# }<br />

exit 0<br />

dc<br />

# One might well wonder whether a shell script is appropriate for<br />

#+ an application as complex and computation−intensive as a simulation.<br />

#<br />

# There are at least two justifications.<br />

# 1) As a proof of concept: to show it can be done.<br />

# 2) To prototype and test the algorithms before rewriting<br />

#+ it in a compiled high−level language.<br />

The dc (desk calculator) utility is stack−oriented and uses RPN ("Reverse Polish Notation"). Like bc,<br />

it has much of the power of a programming language.<br />

Chapter 12. External Filters, Programs and Commands 202

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

Saved successfully!

Ooh no, something went wrong!