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

count=XX creates a file of well−scattered pseudorandom numbers. However, assigning these numbers<br />

to a variable in a script requires a workaround, such as filtering through od (as in above example) or<br />

using dd (see Example 12−42).<br />

There are also other means of generating pseudorandom numbers in a script. Awk provides a convenient<br />

means of doing this.<br />

Example 9−27. Pseudorandom numbers, using awk<br />

#!/bin/bash<br />

# random2.sh: Returns a pseudorandom number in the range 0 − 1.<br />

# Uses the awk rand() function.<br />

AWKSCRIPT=' { srand(); print rand() } '<br />

# Command(s) / parameters passed to awk<br />

# Note that srand() reseeds awk's random number generator.<br />

echo −n "Random number between 0 and 1 = "<br />

echo | awk "$AWKSCRIPT"<br />

exit 0<br />

# Exercises:<br />

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

# 1) Using a loop construct, print out 10 different random numbers.<br />

# (Hint: you must reseed the "srand()" function with a different seed<br />

# in each pass through the loop. What happens if you fail to do this?)<br />

# 2) Using an integer multiplier as a scaling factor, generate random numbers<br />

# in the range between 10 and 100.<br />

# 3) Same as exercise #2, above, but generate random integers this time.<br />

9.7. The Double Parentheses Construct<br />

Similar to the let command, the ((...)) construct permits arithmetic expansion and evaluation. In its simplest<br />

form, a=$(( 5 + 3 )) would set "a" to "5 + 3", or 8. However, this double parentheses construct is also a<br />

mechanism for allowing C−type manipulation of variables in Bash.<br />

Example 9−28. C−type manipulation of variables<br />

#!/bin/bash<br />

# Manipulating a variable, C−style, using the ((...)) construct.<br />

echo<br />

(( a = 23 )) # Setting a value, C−style, with spaces on both sides of the "=".<br />

echo "a (initial value) = $a"<br />

(( a++ )) # Post−increment 'a', C−style.<br />

Chapter 9. Variables Revisited 101

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

Saved successfully!

Ooh no, something went wrong!