Bash Functions

Here are some example BASH functions. For more information, see the online BASH Function documentation.

Declaring Functions

A BASH function must first be declared. One of the two methods can be used to declare a BASH function:

Method #1: function name compound-command

function say_goodbye {
    echo "goodbye"
}

Method #2: name() compound-command

say_hello() {
    echo "hello"
}

Using Functions

Just call the name as you would any other simple command:

say_hello
hello

Passing Variables

Pass variables into the function by space delimited fields and accept parameters using $1, $2 and so on.

my_function() {
    echo "$1"
}

Example:

my_function hello this is a test
hello

To expand all variable parameters inside the function, use $@

log() {
    echo "[$(date)]: $@"
}
log this is a test
[Sun Jun 22 10:21:26 PDT 2008]: this is a test

Return Codes

Functions return an exit status to their caller:

subtest() {
return 1
}

The function will return 1:

subtest || echo "Returned: $?"
Returned: 1

Since the function returned 1, it failed the test of || (or).