Bash functions are a powerful tool in shell scripting that allow you to organize and reuse code. They provide modularity, enhance readability, and make scripts easier to maintain. In this tutorial, we will learn how to define function and use them in your bash scripts.

Defining Functions:

To define a function in Bash, we use function name followed by pair of parentheses. We use a code block using curly braces. The code between these curly braces is the function body.

1function_name () {
2  # Function body
3  # Execute commands
4}

Another way to define a function in bash is using reserved keyword function.

1function func_name() {
2    # function body
3}

Passing Arguments:

Bash allows you to pass arguments to functions when they are called. These arguments can be accessed within the function using special variables like command line arguments.

  1. $1, $2, $3, etc. represent command line arguments passed to the function.
  2. $@ represents all arguments passed as an array.
  3. $# represents the total number of arguments passed.

Here’s an example that demonstrates how to pass and access arguments within a bash function:

1#!/bin/bash
2my_function() {
3  echo "The first argument is: $1"
4  echo "The second argument is: $2"
5}
6
7my_function hello world

Output

The first argument is: hello
The second argument is: world

Returning Values from Functions:

In Bash, values can be returned from a function using the return statement followed by an integer value representing an exit code. The exit code conveys the outcome or status of the function execution.

1my_function() {
2  # Perform actions or calculations
3  return 42
4}
5
6result=$(my_function)
7echo "Return value: $result"

Understanding Exit Codes:

Exit codes have several purposes when it comes to bash functions.

  1. An exit code of 0 indicates success or that the function executed without encountering any errors.
  2. Non-zero exit codes, typically in the range 1-255, indicate an error or some other specific condition.
  3. Exit codes can be used to control the flow of a script by checking for specific conditions or handling errors.

To access the exit code of a function, you can use $?, which captures the last command’s exit status in Bash.

1my_function
2if [[ $? -eq 0 ]]; then
3  echo "Function executed successfully"
4else
5  echo "Function encountered an error"
6fi