Skip to Main Content
bash Pocket Reference
book

bash Pocket Reference

by Arnold Robbins
May 2010
Beginner to intermediate content levelBeginner to intermediate
130 pages
3h 20m
English
O'Reilly Media, Inc.
Content preview from bash Pocket Reference

Functions

A shell function is a grouping of commands within a shell script. Shell functions let you modularize your program by dividing it up into separate tasks. This way, the code for each task is not repeated every time you need to perform the task. The POSIX shell syntax for defining a function follows the Bourne shell:

name () {
    function body's code comes here
} [redirections]

Functions are invoked just as are regular shell built-in commands or external commands. The command-line parameters $1, $2, and so on receive the function’s arguments, temporarily hiding the global values of $1, etc. For example:

# fatal --- print an error message and die:

fatal () {
    # Messages go to standard error.
    echo "$0: fatal error:" "$@" >&2
    exit 1
}
…
if [ $# = 0 ]    # not enough arguments
then
    fatal not enough arguments
fi

A function may use the return command to return an exit value to the calling shell program. Be careful not to use exit from within a function unless you really wish to terminate the entire program.

Per the POSIX standard, any redirections given with the function definition are evaluated when the function executes, not when it is defined.

Bash allows you to define functions using a slightly different syntax, as follows:

function name [()] { body } [redirections]

When using the function keyword, the parentheses following the function name are optional.

Functions share traps with the “parent” shell as described in the following table.

Trap type

Shared/not shared

Signal-based traps

Shared ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Bash Pocket Reference, 2nd Edition

Bash Pocket Reference, 2nd Edition

Arnold Robbins
bash Quick Reference

bash Quick Reference

Arnold Robbins
Mastering Bash

Mastering Bash

Giorgio Zarrelli

Publisher Resources

ISBN: 9781449388669Errata Page