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

Arrays lend themselves, to some extent, to emulating data structures for which Bash has no native support.<br />

Example 26−8. Emulating a push−down stack<br />

#!/bin/bash<br />

# stack.sh: push−down stack simulation<br />

# Similar to the CPU stack, a push−down stack stores data items<br />

#+ sequentially, but releases them in reverse order, last−in first−out.<br />

BP=100<br />

SP=$BP<br />

Data=<br />

# Base Pointer of stack array.<br />

# Begin at element 100.<br />

# Stack Pointer.<br />

# Initialize it to "base" (bottom) of stack.<br />

# Contents of stack location.<br />

# Must use local variable,<br />

#+ because of limitation on function return range.<br />

declare −a stack<br />

push()<br />

{<br />

if [ −z "$1" ]<br />

then<br />

return<br />

fi<br />

let "SP −= 1"<br />

stack[$SP]=$1<br />

# Push item on stack.<br />

# Nothing to push?<br />

# Bump stack pointer.<br />

return<br />

}<br />

pop()<br />

{<br />

Data=<br />

# Pop item off stack.<br />

# Empty out data item.<br />

if [ "$SP" −eq "$BP" ] # Stack empty?<br />

then<br />

return<br />

fi # This also keeps SP from getting past 100,<br />

#+ i.e., prevents a runaway stack.<br />

Data=${stack[$SP]}<br />

let "SP += 1"<br />

return<br />

}<br />

# Bump stack pointer.<br />

status_report()<br />

# Find out what's happening.<br />

{<br />

echo "−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−"<br />

echo "REPORT"<br />

echo "Stack Pointer = $SP"<br />

echo "Just popped \""$Data"\" off the stack."<br />

echo "−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−"<br />

echo<br />

}<br />

Chapter 26. Arrays 304

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

Saved successfully!

Ooh no, something went wrong!