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.

Chapter 23. Functions<br />

Like "real" programming languages, Bash has functions, though in a somewhat limited implementation. A<br />

function is a subroutine, a code block that implements a set of operations, a "black box" that performs a<br />

specified task. Wherever there is repetitive code, when a task repeats with only slight variations, then consider<br />

using a function.<br />

function function_name {<br />

command...<br />

}<br />

or<br />

function_name () {<br />

command...<br />

}<br />

This second form will cheer the hearts of C programmers (and is more portable).<br />

As in C, the function's opening bracket may optionally appear on the second line.<br />

function_name ()<br />

{<br />

command...<br />

}<br />

Functions are called, triggered, simply by invoking their names.<br />

Example 23−1. Simple function<br />

#!/bin/bash<br />

funky ()<br />

{<br />

echo "This is a funky function."<br />

echo "Now exiting funky function."<br />

} # Function declaration must precede call.<br />

# Now, call the function.<br />

funky<br />

exit 0<br />

The function definition must precede the first call to it. There is no method of "declaring" the function, as, for<br />

example, in C.<br />

f1<br />

# Will give an error message, since function "f1" not yet defined.<br />

declare −f f1<br />

# This doesn't help either.<br />

Chapter 23. Functions 274

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

Saved successfully!

Ooh no, something went wrong!