Skip to content

Bash syntax: Functions

Jean-Michel Gigault edited this page Jun 6, 2015 · 18 revisions

Functions enable you to structure your code, to increase readability and to avoid repetition of lines of code.


1. Syntax of a function

Declare a function by using the keyword function followed by its name:

function name_of_function
{
    # Lines of code here
}

name_of_function

To simply call the function, put its name at the beginning of a command line. It will cause the code between the two embraces { ... } to be executed.

As a C program, functions may return a numeric value called exit status by using the keyword return. When return is encountered, the execution of the function is stopped and the immediate value after return is returned:

function return_one
{
    # Lines of code executed
    return 1
    # Lines of code NEVER executed
}

return_one         # Call the function
echo $?            # Print the exit status of the last command

2. Local and global variables

GLOBAL_VAR="Hello"
function display_global_and_local
{
    local LOCAL_VAR="World"
    echo "${GLOBAL_VAR} ${LOCAL_VAR}"
}

display_global_and_local
echo "${GLOBAL_VAR} ${LOCAL_VAR}"

3. Arguments of a function

In Bash programming, the arguments of a function are not explicitly declared. As you read it in the chapter "Bash syntax: Variables", the arguments of a script or a function are called positional parameters. They are listed and named like this: $1, $2, $3...

Passing a list of arguments to our function display_center will cause the positional parameters to be declared:

function display_text
{
    echo "$1"
}

display_text "This is the first argument"

$0 is not a positional parameter, it always contains the name of the script that is currently executed.