Computer >> Computer tutorials >  >> Programming >> BASH programming

How to Use Functions in Bash/Shell Scripts, With Examples

This article will explain how to use functions in Bash scripts – helping you to reuse your code and simplify your scripts.

Why write code multiple times when you can write it once and re-use it?

That’s what functions let you do.

This article outlines the use of functions in Bash/Shell scripts.

What is a Function?

function is a piece of re-usable code. Functions can accept parameters, which allow them to perform the same repeatable actions on different inputs.

Functions usually perform any action, output or print results, or return a value for future use.

Why Use a Function?

As an example, you may have a script that sends an email notification that something has occurred. If you wanted to send multiple different emails to multiple recipients, you might write the same email-sending code several times in the script to send the messages.

Using a function, you’d be able to write this code only once, then call it with different recipients, subjects, and messages, with a single line function call rather than duplicated code.

Bash Function Syntax

The syntax for writing functions in Bash/Shell scripts is as follows:

name_of_function () {
    # COMMANDS
    # Optional return value
}

Note that:

  • name_of_function is the name you want to be able to call your function using
    • Alphanumeric characters and underscores only!
  • The function name must be followed by () (standard brackets)
    • Note the spaces around the brackets! They are required!
  • The code you want the function to execute must be wrapped in {} (curly brackets)
    • Any code outside of these curly brackets is NOT part of the function and will not be executed.
  • COMMANDS can be any command that would usually be available on your Linux system
  • You can optionally return a value – see the below example for usage
    • To terminate a function early, you can also call return with no value to exit the function
    • The special $? variable will hold the returned value from the last executed command, making it available elsewhere in your script after the function has been run

Example & Explanation

Here’s an example that illustrates all of the different Bash function elements – with comments explaining what everything is doing.

#!/bin/bash

# Define a global variable - available anywhere in the script as it is not defined inside a function or loop
initial_value=3

# Define a function which does some mathematics
my_math_function () {

    # Get the parameters passed to the function 
    # Parameters are passed after the function name when calling the function, and will be named in order of appearance, starting with $1, then $2, etc
    # Below, these parameter values are assigned to local variables - available only inside the function - so that it's easier to tell what they are
    local multiplier_value=$1
    local addition_value=$2

    # Calculate the result and assign it to a local variable
    # Notice the $(( )) wrapping the calculations - this tells the script to assign the result of these calculations to the results variable, rather than assigning the calculations as a text value
    local result=$(( $initial_value * $multiplier_value + $addition_value ))

    # Print the result to the console
    # Depending on how the function is used, text output from the function can be used to read results from it
    echo $result

    # It is also possible to get output from the function using a return value
    return $result

}

# Call the function with different input parameters
# Parameters are passed to the function by typing them after the function separated by a space
# The function above expects two parameters - a multiplier_value and addition_value

my_math_function 2 4 # Will output 10 (2 * 3 + 4)

my_math_function 3 5 # Will output 14 (3 * 3 + 5)

# The $? is a special variable in Bash scripts which always holds the return value from the last executed command
# It can be used to get the value specified as the return value from the function.

echo $? # Will output 14

# Assign the result of the function to a variable
# This will assign any text outputted by the function (for example using the echo command) to a variable
my_result=$(my_math_function 6 7)
echo $my_result # Will output 25 (6 * 3 + 7)

What is the ‘#!’ in Linux Shell Scripts?

Want to pass values to your shell script (so you can then pass them to the functions in it)? Check out this article.