How to write a function in bash

Last updated on March 2, 2021 by Dan Nanni

When you are writing a complex bash script (or any complex program for that matter), subdividing the functional logic of the script in smaller modules and writing/testing each module is often an effective coding strategy. A modularized bash script not only makes the script easier to understand, but also makes individual modules re-usable. In bash, such modular programming is achieved with bash functions.

Even if you have little coding experience, you are probably familiar with the notion of a function in programming. A function is basically a self-contained block of code that performs a specific task via well-defined input/output interfaces. Let's find out how a bash function is written and how to use a function in bash. This bash tutorial will specifically cover how to create a bash function, how to pass arguments to it, how to call a bash function, how to return a value from a bash function, etc.

Create a Bash Function

You can create (or define) a function using the following format.

function <user-defined-function-name> {
    # body of the function
}

The keyword function before the function name is optional and can be omitted. To be POSIX-compliant, the name of a bash function may not contain any characters other than letters, digits and underscores, and may not start with a digit.

Run a Bash Function

Once a bash function is defined in a bash script, you can call the function in the script. In bash, you need to define a function before calling it, meaning that function definition should come first. Otherwise, you will see "command not found" error. In order to invoke a bash function, simply use the function name.

function test_func {
    echo "This is my first bash function"
}

test_func  # run the function defined above
This is my first bash function

Pass Arguments to a Bash Function

In many cases you want to pass some arguments to a bash function, instead of calling it standalone. In terms of argument passing, a bash function behaves similarly to a regular bash script. Thus, when you pass arguments to a bash function, these arguments are referenced inside the function much like positional parameters passed to a bash script from the command line. For example, the first argument is referenced by $1, the second argument by $2, etc. You can also iterate over a list of all arguments by running a for loop with [email protected]. The total number of arguments passed to a bash function is stored in $#.

In order to pass arguments during function call, simply list the arguments separated by whitspace after the function name. For example, see the following script for argument passing and its execution result.

function test_argument {
    if [ $# -eq 2 ]; then
        local arg1=$1   # first argument
        local arg2=$2   # second argument
    else
        echo "my_func accepts two arguments"
        exit 1
    fi
    echo "First argument: $arg1"
    echo "Second argument: $arg2"
}

# call the function while passing two arguments to it
test_argument 100 "Hello world!"
First argument: 100
Second argument: Hello world!

Exit a Bash Function

If you want to exit a bash function and return to the main script, you can use a built-in command called return inside the function as follows (N is a numeric value).

return N

The digit N is returned to the main script as the exit status of the function. N is optional and can be omitted, in which case the exit status of the function is that of the last command executed inside the function. When return is encountered inside a bash function, it is immediately exited, and control is returned to the main script. So for example, return can be used to break out of a loop and exit a function as illustrated below.

function test_exit {
    i=0
    while : ; do                # infinite loop
        (( i += 1 ))
        if [ $i -gt 3 ]; then   # break out of the loop
            return 1            # and exit if $i > 3
        fi
        echo "i: $i"
    done
    return 0
}

test_exit
echo "[Exit status]: $?"

Note that $? is a special bash variable that stores the exit status of the last executed command. In this example, the last command that was executed is actually the test_return function, and hence 1 is the exit status. The output of this example script is:

i: 1
i: 2
i: 3
[Exit status]: 1

Return a Value from a Bash Function

In some cases you may want your bash function to return a value as an output. The return value could be a string or a numeric value. However, unlike functions supported by other programming languages, bash functions cannot directly return a value as an output. The bash's built-in return command described above is simply a means to deliver the exit status of a function, and this is not returning an arbitrary output from the function.

If your bash function needs to return an output value, there are two ways to do that.

Using a Global Variable

The first method is to rely on a global variable. In a bash script, any variable you declare is treated as a global variable (unless explicitly specified as local), and is visible to all bash functions. If you modify a global variable within a function, that change is visible outside the function. Thus, in order to return a value to the main script, a bash function can simply store the return value in a global variable. Then the main script can read the global variable to retrieve the return value. For example:

function test_return {
    # store the return value in a global variable 'retval'
    retval="Linux rocks!"
}

retval="initial value"  # global variable
test_return
echo "Function output: $retval"
Function output: Linux rocks!

Using echo Command

Another way for a bash function to return a value is by using the echo command, which prints a line of text or string to stdout. Anything that is printed by echo in a bash function can be captured in another variable using command substitution. For example:

function test_return2 {
    local retval="Linux really rocks!"
    echo $retval
}

output=$(test_return2)
echo "Function output: $output"
Function output: Linux really rocks!

As you can see above, the return value of test_return2() is printed by echo, and this printed value is then stored in another variable output by command substitution.

If you find this tutorial helpful, I recommend you check out the series of bash shell scripting tutorials provided by Xmodulo.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal (Credit Card) or Bitcoin (1M161JGAkz3oaHNvTiPFjNYkeABox8rb4g).

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for Us ‒ Feed ‒ Powered by DigitalOcean