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

f1<br />

# Still an error message.<br />

# However...<br />

f1 ()<br />

{<br />

echo "Calling function \"f2\" from within function \"f1\"."<br />

f2<br />

}<br />

f2 ()<br />

{<br />

echo "Function \"f2\"."<br />

}<br />

f1 # Function "f2" is not actually called until this point,<br />

#+ although it is referenced before its definition.<br />

# This is permissable.<br />

# Thanks, S.C.<br />

It is even possible to nest a function within another function, although this is not very useful.<br />

f1 ()<br />

{<br />

}<br />

f2 () # nested<br />

{<br />

echo "Function \"f2\", inside \"f1\"."<br />

}<br />

f2 # Gives an error message.<br />

# Even a preceding "declare −f f2" wouldn't help.<br />

echo<br />

f1 # Does nothing, since calling "f1" does not automatically call "f2".<br />

f2 # Now, it's all right to call "f2",<br />

#+ since its definition has been made visible by calling "f1".<br />

# Thanks, S.C.<br />

Function declarations can appear in unlikely places, even where a command would otherwise go.<br />

ls −l | foo() { echo "foo"; } # Permissable, but useless.<br />

if [ "$USER" = bozo ]<br />

then<br />

bozo_greet () # Function definition embedded in an if/then construct.<br />

{<br />

echo "Hello, Bozo."<br />

}<br />

fi<br />

bozo_greet<br />

# Works only for Bozo, and other users get an error.<br />

Chapter 23. Functions 275

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

Saved successfully!

Ooh no, something went wrong!