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

CopyArray=CpArray_Mac<br />

# Statement Builder<br />

Hype()<br />

{<br />

# Hype the array named $1.<br />

# (Splice it together with array containing "Really Rocks".)<br />

# Return in array named $2.<br />

local −a TMP<br />

local −a hype=( Really Rocks )<br />

}<br />

$($CopyArray $1 TMP)<br />

TMP=( ${TMP[@]} ${hype[@]} )<br />

$($CopyArray TMP $2)<br />

declare −a before=( <strong>Advanced</strong> Bash Scripting )<br />

declare −a after<br />

echo "Array Before = ${before[@]}"<br />

Hype before after<br />

echo "Array After = ${after[@]}"<br />

# Too much hype?<br />

echo "What ${after[@]:3:2}?"<br />

declare −a modest=( ${after[@]:2:1} ${after[@]:3:2} )<br />

# −−−− substring extraction −−−−<br />

echo "Array Modest = ${modest[@]}"<br />

# What happened to 'before' ?<br />

echo "Array Before = ${before[@]}"<br />

exit 0<br />

−−<br />

Arrays permit deploying old familiar algorithms as shell scripts. Whether this is necessarily a good idea is left<br />

to the reader to decide.<br />

Example 26−6. An old friend: The Bubble Sort<br />

#!/bin/bash<br />

# bubble.sh: Bubble sort, of sorts.<br />

# Recall the algorithm for a bubble sort. In this particular version...<br />

# With each successive pass through the array to be sorted,<br />

#+ compare two adjacent elements, and swap them if out of order.<br />

# At the end of the first pass, the "heaviest" element has sunk to bottom.<br />

# At the end of the second pass, the next "heaviest" one has sunk next to bottom.<br />

# And so forth.<br />

# This means that each successive pass needs to traverse less of the array.<br />

Chapter 26. Arrays 299

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

Saved successfully!

Ooh no, something went wrong!