Bash Function & How to Use It {Variables, Arguments, Return} (2023)


A bash function is a method used in shell scripts to group reusable code blocks. This feature is available for most programming languages, known under different names such as procedures, methods, or subroutines.

This article provides a complete overview of bash functions, how they work, and how to use them.

Bash Function & How to Use It {Variables, Arguments, Return} (1)


  • A system running Linux.
  • Access to the terminal and Bash shell.
  • A text editor for writing bash scripts (the guide uses Vim).

Note: The Bash (Bourne Again SHell) is considered the default shell in this tutorial. If your default shell is different, try adding the #!/bin/bash shebang to the beginning of the scripts.

What Are Bash Functions?

A bash function is a technique for grouping reusable bits of code under one name for later use. The bash function is like a script within a script.

Bash Function & How to Use It {Variables, Arguments, Return} (2)

Using functions in bash scripting comes with two benefits:

1. A function is read directly into the shell's memory and stored for later use. Since computer memory is not an issue nowadays, using functions is faster than repeating code.

2. Functions help organize long shell scripts into modular and reusable code blocks. The chunks are easier to develop and maintain.

How to Use Bash Functions?

There are two ways to implement Bash functions:

  • Inside a shell script, where the function definition must be before any calls on the function.
  • Alongside other bash alias commands and directly in the terminal as a command.

To use bash functions, follow the outlines below.

Bash Function Syntax

There are two different ways to declare a bash function:

1. The most widely used format is:

<function name> () { <commands> }

Alternatively, the same function can be one line:

<function name> () { <commands>; }

2. The alternative way to write a bash function is using the reserved word function:

function <function name> { <commands>}

Or in one line:

function <function name> { <commands>; }

Take note of the following behaviors and tips when using functions:

  • When writing in one line, the commands must end with a semicolon (;), whether in bash scripts or the terminal directly.
  • Adding the function reserved word makes parentheses optional.
  • The commands between the curly braces { <commands> } are called the function's body. The body can contain any number of declarations, variables, loops, or conditional statements.
  • Try to use descriptive names for functions. Although not necessary when testing functions and commands, descriptive names help in settings where other developers look at the code.

How to Declare and Call a Function?

A function does not execute when declared. The function's body executes when invoked after declaration. Follow the steps below to create a bash script with various syntax options:

1. Using your favorite text editor, create a shell script called syntax. If you're using Vim, run the following line in the terminal:


2. Add the code below to the shell script:

# Declaring functions using the reserved word function# Multilinefunction f1 { echo Hello I\'m function 1 echo Bye!}# One linefunction f2 { echo Hello I\'m function 2; echo Bye!; }# Declaring functions without the function reserved word# Multilinef3 () { echo Hello I\'m function 3 echo Bye!}# One linef4 () { echo Hello I\'m function 4; echo Bye!; }# Invoking functionsf4f3f2f1
Bash Function & How to Use It {Variables, Arguments, Return} (3)

The script does the following:

  • Lines 4-9 demonstrate how to define a function using the function reserved word. The function f1 uses a multiline syntax in lines 4-6, whereas f2 uses one line syntax on line 9.
  • Lines 13-18 show the more familiar syntax. f3 is a multiline function defined in lines 13-16, while f4 on line 18 is the single line equivalent.
  • Lines 21-24 invoke the previously defined functions and execute the commands in the corresponding function's bodies. The calls are made in reversed order from the definition.

3. Save the script and close Vim:


4. Make the file executable:

chmod +x

5. Lastly, run the script to see the output:

Bash Function & How to Use It {Variables, Arguments, Return} (4)

How to Declare and Call a Function in the Terminal?

To declare and use a function in the terminal:

1. Open the terminal and enter the following line:

my_function () { echo "Hello I'm a function"; echo "Bye!"; }

2. Execute the function by entering the function's name in the terminal:

Bash Function & How to Use It {Variables, Arguments, Return} (5)

The output runs the commands in the function's body.

The function only stays defined in the current terminal session. To save for future sessions, add the code to the ~/.bashrc file.

Where is a Bash Function Defined?

To see where a bash function is defined and its contents, enter the following commands in the terminal:

1. Run the bash shell in debugger mode:

bash --debugger

2. Check the function's source file with:

declare -F <function name>

For example:

declare -F my_function
Bash Function & How to Use It {Variables, Arguments, Return} (6)

The output prints the function's name, the line number, and the file location where the function definition is.

3. To see the function's contents, run:

declare -f <function name>

For example:

declare -f my_function
Bash Function & How to Use It {Variables, Arguments, Return} (7)

The declare built-in in debugging mode allows viewing the function's contents and location without running the code.

Note: Learn everything you need to know about using the Bash declare statement.

How to Delete a Bash Function?

If you need to free up a namespace occupied by a function in the current terminal session, run:

unset <function name>

For example:

unset my_function
Bash Function & How to Use It {Variables, Arguments, Return} (8)

The function is no longer available in the current terminal session. However, if the code is in the ~/.bashrc file, everything is restored to normal in the next session.

Bash Function Variables

The variables in bash are global by default and accessible from anywhere, including function bodies. Variables defined inside a function are also global.Adding the keyword local makes the term accessible only within the function and the child functions/processes.

In dynamic scoping, a local variable shadows a global variable when the two carry the same name.

Try the following bash script to demonstrate how function variables work in bash:

1. Create a script called


2. Add the following code to the script:

var1=1var2=1change() { echo Inside function echo Variable 1 is: $var1 echo Variable 2 is: $var2 local var1=5 var2=5 echo echo After change inside function echo Variable 1 is locally $var1 echo Variable 2 is globally $var2}echo Before function invocationecho Variable 1 is: $var1echo Variable 2 is: $var2echochangeechoecho After function invocationecho Variable 1 is: $var1echo Variable 2 is: $var2
Bash Function & How to Use It {Variables, Arguments, Return} (9)

The script shows the following:

  • Lines 1-2 declare variables var1 and var2 and set them both to 1.
  • Lines 5-6 are inside the function's body and print the variables to the console. Since the variable scope is global, the original values print out.
  • Line 7 declares a new local variable with the same name as the global variable var1. The local var1 shadows the global var1 value due to dynamic scoping.
  • Line 8 changes the value of the global var2 variable.
  • Lines 14-22 print the variable values before and after calling the function.

3. Save the script and exit Vim:


4. Change the file permissions to executable:

chmod +x

5. Run the script and analyze the results:

Bash Function & How to Use It {Variables, Arguments, Return} (10)

The variable values print to the console through the changes made in the script.

Bash Function Arguments

To pass arguments to a function, add the parameters after the function call separated by spaces. The table below outlines the available options when working with bash function arguments.

Argument Role
$0Reserves the function's name when defined in the terminal. When defined in a bash script, $0 returns the script's name and location.
$1, $2, etc.Corresponds to the argument's position after the function name.
$#Holds the count of positional arguments passed to the function.
[emailprotected] and $*Hold the positional arguments list and function the same when used this way.
"[emailprotected]"Expands the list to separate strings. For example "$1", "$2", etc.
"$*"Expands the list into a single string, separating parameters with a space. For example "$1 $2" etc.

Follow the steps below to test how the various arguments work in a function.

1. Create a script called arguments:


2. Add the following code into the script:

arguments () { echo The function location is $0 echo There are $# arguments echo "Argument 1 is $1" echo "Argument 2 is $2" echo "<[emailprotected]>" and "<$*>" are the same. echo List the elements in a for loop to see the difference! echo "* gives:" for arg in "$*"; do echo "<$arg>"; done echo "@ gives:" for arg in "[emailprotected]"; do echo "<$arg>"; done}arguments hello world

3. Save the script and exit Vim:


4. Make the script executable:

chmod +x

5. Execute the script:

Bash Function & How to Use It {Variables, Arguments, Return} (11)

The output displays descriptive messages for each argument used.

Bash Function Return

Bash functions differ from most programming languages when it comes to returning a value from a function. By default, bash returns the exit status of the last executed command in the function's body.

The script below shows how to specify the exit status using return:

1. Create a script and name it


2. Add the following function to the file:

test_function() { echo Test return 100}echo The function\'s output is: test_functionecho The exit status is:echo $?

3. Save and close the text editor:


4. Change the permissions:

chmod +x

5. Run the script to see the function's output and exit status:


An alternative method is to echo the function's result and assign the output to a variable. Edit the script with the following code:

test_function() { echo Test}result=$(test_function)echo $result is saved in a variable for later use

This method mimics how most programming languages work when using functions.

Note: Check out our bash scripting tutorial on how to run a bash script that features several methods explained.


After going through this tutorial, you should know how to use functions in bash scripting. Next, use our git commands cheat sheet to help you automate repetitive git tasks using bash functions.

Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated: 04/22/2023

Views: 6120

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.