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 a name. In this example, we will create a function for displaying text in the middle of a line in a terminal, we call it display_center:

function display_center
{
    # Lines of code here
}

Calling the function display_center will cause the code between the two embraces { ... } to be executed. As a C program, functions may return a numeric value by using the keyword ret. When ret is encountered, the execution of the function is stopped and the immediate value after ret is returned:

function return_zero
{
    # Lines of code are executed
    ret 0
    # Lines of code NEVER executed
}

2. Local and global variables


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 automaticaly declared:

function display_center
{
    echo "$1"
}