Bash Functions (original) (raw)

Bash Functions

A Bash function is a reusable block of commands that can be called multiple times within a script. Functions help you make your bash scripts more readable, easier to maintain, and less repetitive.

While Bash functions are more limited than those in other programming languages, they are still very powerful for shell scripting.

In this guide, we will cover the basics of Bash functions and show you how to use them in your shell scripts.

Defining Bash Functions

There are two different ways to define a function in Bash.

  1. The first format starts with the function name, followed by parentheses. This is the preferred and most used syntax.
function_name () {  
  commands  
}  

Single line version:

function_name () { commands; }  
  1. The second format starts with the reserved word function, followed by the function name.
function function_name {  
  commands  
}  

Single line version:

function function_name { commands; }  

Important points to note:

Example: Hello World Function

To understand this better, take a look at the following example:

~/hello_world.sh

#!/bin/bash

hello_world () {
   echo 'Hello, World.'
}

hello_world

Let’s analyze the code line by line:

Running the script prints:

Variable Scope in Bash Functions

Global Variables

Local Variables

Example: Variable Scope

To better illustrate how variable scope works in Bash, let’s consider this example:

~/variables_scope.sh

#!/bin/bash

var1='A'
var2='B'

my_function () {
  local var1='C'
  var2='D'
  echo "Inside function: var1: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>v</mi><mi>a</mi><mi>r</mi><mn>1</mn><mo separator="true">,</mo><mi>v</mi><mi>a</mi><mi>r</mi><mn>2</mn><mo>:</mo></mrow><annotation encoding="application/x-tex">var1, var2: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8389em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">1</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">2</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>var2"
}

echo "Before executing function: var1: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>v</mi><mi>a</mi><mi>r</mi><mn>1</mn><mo separator="true">,</mo><mi>v</mi><mi>a</mi><mi>r</mi><mn>2</mn><mo>:</mo></mrow><annotation encoding="application/x-tex">var1, var2: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8389em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">1</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">2</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>var2"

my_function

echo "After executing function: var1: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>v</mi><mi>a</mi><mi>r</mi><mn>1</mn><mo separator="true">,</mo><mi>v</mi><mi>a</mi><mi>r</mi><mn>2</mn><mo>:</mo></mrow><annotation encoding="application/x-tex">var1, var2: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8389em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">1</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">2</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>var2"

The script starts by defining two global variables var1 and var2. Then there is an function that sets a local variable var1 and modifies the global variable var2.

If you run the script, you should see the following output:

Before executing function: var1: A, var2: B
Inside function: var1: C, var2: D
After executing function: var1: A, var2: D

From the output above, we can conclude that:

Return Values in Bash Functions

Unlike functions in “real” programming languages, Bash functions do not return values when called. When a bash function completes, its return value is the status of the last statement executed in the function:

The return status can be specified using the return keyword, and it is assigned to the variable $?. The return statement terminates the function. You can think of it as the function’s exit status.

~/return_values.sh

#!/bin/bash

my_function () {
  echo "some result"
  return 55
}

my_function
echo $?
some result
55

Returning Data from a Function

Since Bash cannot return arbitrary values directly, we need to use other methods. There are two common workarounds.

  1. Using a Global Variable:
    The simplest option is to assign the result of the function to a global variable:
    ~/return_values.sh
#!/bin/bash  
my_function () {  
  func_result="some result"  
}  
my_function  
echo $func_result  
some result  
  1. Using Standard Output (Recommended)
    Another option is to send the value to stdout using echoor printf. This approach is cleaner and avoids unnecessary global variables:
    ~/return_values.sh
#!/bin/bash  
my_function () {  
  local func_result="some result"  
  echo "$func_result"  
}  
func_result="$(my_function)"  
echo $func_result  
some result  

Instead of simply executing the function, which prints the message to stdout, we assign the function’s output to the func_result variable using the $() command substitution. The variable can later be used as needed.

Passing Arguments to Functions

Arguments are passed to a function by placing them after the function name, separated by a space. It is a good practice to double-quote the arguments to avoid the misparsing of an argument with spaces in it.

function_name arg1 arg2 arg3

Special Variables

Here is an example:

~/passing_arguments.sh

#!/bin/bash

greeting () {
  echo "Hello $1"
}

greeting "Zoe"
Hello Zoe

Conclusion

A Bash function is a block of reusable code designed to perform a particular operation. Once defined, the function can be called multiple times within a script.

Functions are especially useful for repeating tasks, simplifying complex scripts, and creating readable and modular code.

You can also read about how to use a Bash function to create a memorable shortcut command(alias) for a longer command.

If you have any questions or feedback, feel free to leave a comment.

If you like our content, please consider buying us a coffee.
Thank you for your support!

Buy me a coffee

Sign up to our newsletter and get our latest tutorials and news straight to your mailbox.

Write a comment