Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 11. Functions<br />
In this chapter, we will discuss<br />
♦ What functions are<br />
♦ Creation and displaying of functions from the command line<br />
♦ Functions in scripts<br />
♦ Passing arguments to functions<br />
♦ When to use functions<br />
11.1. Introduction<br />
11.1.1. What are functions?<br />
Shell functions are a way to group commands for later execution, using a single name for this group, or<br />
routine. The name of the routine must be unique within the shell or script. All the commands that make up a<br />
function are executed like regular commands. When calling on a function as a simple command name, the list<br />
of commands associated with that function name is executed. A function is executed within the shell in which<br />
it has been declared: no new process is created to interpret the commands.<br />
Special built-in commands are found before shell functions during command lookup. The special built-ins are:<br />
break, :, ., continue, eval, exec, exit, export, readonly, return, set, shift, trap and unset.<br />
11.1.2. Function syntax<br />
Functions either use the syntax<br />
function FUNCTION { COMMANDS; }<br />
or<br />
FUNCTION () { COMMANDS; }<br />
Both define a shell function FUNCTION. The use of the built-in command function is optional; however, if<br />
it is not used, parentheses are needed.<br />
The commands listed between curly braces make up the body of the function. These commands are executed<br />
whenever FUNCTION is specified as the name of a command. The exit status is the exit status of the last<br />
command executed in the body.<br />
Common mistakes<br />
The curly braces must be separated from the body by spaces, otherwise they are interpreted in the wrong<br />
way.<br />
The body of a function should end in a semicolon or a newline.<br />
Chapter 11. Functions 131