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

echo<br />

echo "$count: ${Countries[@]}" # Print resultant array at end of each pass.<br />

echo<br />

let "count += 1"<br />

# Increment pass count.<br />

done<br />

# End of outer loop<br />

# All done.<br />

exit 0<br />

−−<br />

Is it possible to nest arrays within arrays?<br />

#!/bin/bash<br />

# Nested array.<br />

# Michael Zick provided this example.<br />

AnArray=( $(ls −−inode −−ignore−backups −−almost−all \<br />

−−directory −−full−time −−color=none −−time=status \<br />

−−sort=time −l ${PWD} ) ) # Commands and options.<br />

# Spaces are significant . . . and don't quote anything in the above.<br />

SubArray=( ${AnArray[@]:11:1} ${AnArray[@]:6:5} )<br />

# Array has two elements, each of which is in turn an array.<br />

echo "Current directory and date of last status change:"<br />

echo "${SubArray[@]}"<br />

exit 0<br />

−−<br />

Arrays enable implementing a shell script version of the Sieve of Eratosthenes. Of course, a<br />

resource−intensive application of this nature should really be written in a compiled language, such as C. It<br />

runs excruciatingly slowly as a script.<br />

Example 26−7. Complex array application: Sieve of Eratosthenes<br />

#!/bin/bash<br />

# sieve.sh<br />

# Sieve of Eratosthenes<br />

# Ancient algorithm for finding prime numbers.<br />

# This runs a couple of orders of magnitude<br />

# slower than the equivalent C program.<br />

LOWER_LIMIT=1 # Starting with 1.<br />

UPPER_LIMIT=1000 # Up to 1000.<br />

# (You may set this higher... if you have time on your hands.)<br />

PRIME=1<br />

NON_PRIME=0<br />

Chapter 26. Arrays 301

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

Saved successfully!

Ooh no, something went wrong!