| Article Index |
|---|
| Functions in Shell Scripting |
| Page 2 |
| Page 3 |
| Page 4 |
| Page 5 |
| Page 6 |
| Page 7 |
| Page 8 |
| All Pages |
Functions in Shell Scripting
- Table of Contents
- 1. Complex Functions and Function Complexities
- 2. Local Variables
- 3. Recursion Without Local Variables
Like "real" programming languages, Bash has functions, though in a somewhat limited implementation. A function is a subroutine, a code block that implements a set of operations, a "black box" that performs a specified task. Wherever there is repetitive code, when a task repeats with only slight variations in procedure, then consider using a function.
function function_name {
command...
}
function_name () {
command...
}
This second form will cheer the hearts of C programmers (and is more portable).
As in C, the function's opening bracket may optionally appear on the second line.
function_name ()
{
command...
}
![]() | A function may be "compacted" into a single line.
In this case, however, a semicolon must follow the final command in the function.
|
Functions are called, triggered, simply by invoking their names. A function call is equivalent to a command.
Example 23-1. Simple functions
#!/bin/bash |
The function definition must precede the first call to it. There is no method of "declaring" the function, as, for example, in C.
f1 |
It is even possible to nest a function within another function, although this is not very useful.
f1 () |





