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

# You will therefore notice a speeding up in the printing of the later passes.<br />

exchange()<br />

{<br />

# Swaps two members of the array.<br />

local temp=${Countries[$1]} # Temporary storage<br />

#+ for element getting swapped out.<br />

Countries[$1]=${Countries[$2]}<br />

Countries[$2]=$temp<br />

}<br />

return<br />

declare −a Countries # Declare array,<br />

#+ optional here since it's initialized below.<br />

# Is it permissable to split an array variable over multiple lines<br />

#+ using an escape (\)?<br />

# Yes.<br />

Countries=(Netherlands Ukraine Zaire Turkey Russia Yemen Syria \<br />

Brazil Argentina Nicaragua Japan Mexico Venezuela Greece England \<br />

Israel Peru Canada Oman Denmark Wales France Kenya \<br />

Xanadu Qatar Liechtenstein Hungary)<br />

# "Xanadu" is the mythical place where, according to Coleridge,<br />

#+ Kubla Khan did a pleasure dome decree.<br />

clear<br />

# Clear the screen to start with.<br />

echo "0: ${Countries[*]}" # List entire array at pass 0.<br />

number_of_elements=${#Countries[@]}<br />

let "comparisons = $number_of_elements − 1"<br />

count=1 # Pass number.<br />

while [ "$comparisons" −gt 0 ]<br />

do<br />

# Beginning of outer loop<br />

index=0 # Reset index to start of array after each pass.<br />

while [ "$index" −lt "$comparisons" ] # Beginning of inner loop<br />

do<br />

if [ ${Countries[$index]} \> ${Countries[`expr $index + 1`]} ]<br />

# If out of order...<br />

# Recalling that \> is ASCII comparison operator<br />

#+ within single brackets.<br />

# if [[ ${Countries[$index]} > ${Countries[`expr $index + 1`]} ]]<br />

#+ also works.<br />

then<br />

exchange $index `expr $index + 1` # Swap.<br />

fi<br />

let "index += 1"<br />

done # End of inner loop<br />

let "comparisons −= 1" # Since "heaviest" element bubbles to bottom,<br />

#+ we need do one less comparison each pass.<br />

Chapter 26. Arrays 300

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

Saved successfully!

Ooh no, something went wrong!