Bash functions are reusable blocks of commands that improve script readability and prevent task duplication by letting other parts of a script reference them by name. A function groups commands that perform a specific task, and you can call it from anywhere in a script or an interactive shell session. This guide covers the two ways to define a function, how to call one and pass arguments, how to return custom status codes, how functions interact with global and local variables, and how to combine functions with loops and conditional statements. By the end, you'll have a working set of Bash functions that accept arguments, return values, and run inside loops and conditional logic.

1. Learn the Bash Function Syntax

You can define a function in Bash using two formats: the function name followed by parentheses (), or the function keyword followed by a name.

  • Bash function syntax with parentheses ():

    function_name () { #commands-to-run } 

    Inline parenthesis format:

    function_name () { #commands-to-run; } 
  • Bash function syntax with the function keyword:

    function function_name { #commands-to-run } 

    Inline function format:

    function function_name { #commands-to-run; } 

2. Create Bash Functions

1. Create a new inline greet function using the parentheses method in a shell environment:

$ greet () { echo "Hello World!"; }; greet 

Output:

Hello World! 

2. Create an inline greet function using the function keyword method:

$ function greet () { echo "Hello World!"; }; greet 

Output:

Hello World! 

3. Create a new greet.sh script:

$ nano greet.sh 

4. Add the following contents to the greet.sh file:

#!/bin/bash function greet () { echo 'Hello World! This is a function' } greet 

Save and close the file. The greet function outputs the Hello World! This is a function message with echo when the script calls the function.

5. Run the script using Bash:

$ bash greet.sh 

Output:

Hello World! This is a function 

3. Call Bash Functions

Calling a function invokes the commands inside it. You can call a function by name and pass optional arguments to it, using:

  • $0: the function name.
  • $1, $2, etc: positional function parameters.
  • ${!variable}: indirect referencing of a variable's value.
  • $#: the number of positional parameters passed to a function.
  • $*: all positional parameters expanded into a single string.
  • $@: positional parameters expanded as separate quoted strings.

1. Create a new call-functions.sh script:

$ nano call-functions.sh 

2. Add the following contents to the call-functions.sh file:

#!/bin/bash greet="Hello World!" function greeting () { echo $greet } echo "Calling the function" greeting 

Save and close the file. The greeting function imports the greet variable and outputs it with echo when the script calls the function.

3. Run the script using Bash:

$ bash call-functions.sh 

Output:

Calling the function Hello World! 

4. Create another call-function-args.sh script:

$ nano call-function-args.sh 

5. Add the following contents to the call-function-args.sh file:

#!/bin/bash function calculate() { local a=$1 local b=$2 local sum=$((a + b)) echo "The sum of $a and $b is: $sum" } calculate 5 10 

Save and close the file. The script calls calculate with the $1 and $2 arguments, forwarding them into the local a and b variables; sum stores their total and echo prints the result.

6. Run the script using Bash:

$ bash call-function-args.sh 

Output:

The sum of 5 and 10 is: 15 

4. Return a Status from a Function

Unlike other programming languages, Bash functions don't return status codes automatically — a function returns the status of its last command by default: 0 for success, or a non-zero number from 1 to 255 for failure. Use the return statement to set a specific custom status code.

1. Create a new return-function.sh script:

$ nano return-function.sh 

2. Add the following contents to the return-function.sh file:

#!/bin/bash function greetings() { echo "Hello World!" return 200 } greetings func_status=$? echo "The Return status is: $func_status" 

Save and close the file. The script calls greetings to print a Hello World! message, stores the function's exit status in $?, and returns a non-zero 200 status code.

3. Run the script using Bash:

$ bash return-function.sh 

Output:

Hello World! The Return status is: 200 

5. Use the Exit Command in a Function

The exit command terminates an entire function and returns an exit status code. It's similar to return, but stops all further execution — useful when you need to bail out on an error or unmet condition.

1. Create a new exit-function.sh script:

$ nano exit-function.sh 

2. Add the following contents to the exit-function.sh file:

#!/bin/bash function greetings() { echo "Hello World!" exit 2 echo "This can't run, the script has exited" } greetings 

Save and close the file. The exit command stops the function from running any further and returns a non-zero exit code of 2.

3. Run the script using Bash:

$ bash exit-function.sh 

Output:

Hello World! 

6. Use Variables with Functions

Variables in Bash store data that functions can use to hold repeated values or manipulate data. Functions support both:

  • Global variables: declared outside a function body and accessible anywhere in the script.
  • Local variables: declared inside a function with the local keyword and accessible only inside that function.

1. Create a new var-function.sh script:

$ nano var-function.sh 

2. Add the following contents to the var-function.sh file:

#!/bin/bash greeting="Hello" read username function greetings() { local name="$1" echo "$greeting, $name!" } greetings $username 

Save and close the file. The greetings function declares a local name variable and reads the global greeting variable. It takes the user's input from username as an argument, and echo combines both variables into a single message.

3. Run the script using Bash:

$ bash var-function.sh 

Enter a name such as John Doe when prompted to test the function:

John Doe Hello, John! 

7. Use Functions with Loops

Bash functions work with for, while, and until loops to run repetitive tasks inside or outside a function.

1. Create a new loop-in-function.sh script to use an internal loop:

$ nano loop-in-function.sh 

2. Add the following contents to the loop-in-function.sh file:

#!/bin/bash function count() { local compare="$1" local var=0 for ((var=0; var<compare; var++)); do echo "Current value: $var" done } count 10 

Save and close the file. The count function uses a for loop to increment var and print its value while it's less than the input argument stored in the compare local variable (10).

3. Run the script using Bash:

$ bash loop-in-function.sh 

Output:

Current value: 0 Current value: 1 Current value: 2 Current value: 3 Current value: 4 Current value: 5 Current value: 6 Current value: 7 Current value: 8 Current value: 9 

4. Create another loop-out-functions.sh script to use an external loop:

$ nano loop-out-functions.sh 

5. Add the following contents to the loop-out-functions.sh file:

#!/bin/bash function greetings() { local username="$1" echo "Hello, $username!" } names=("John" "Doe" "Admin" "Jane" "root" ) for username in "${names[@]}"; do greetings "$username" done 

Save and close the file. The greetings function takes username as an argument each time the external for loop calls it, and the loop sets a new value from the names array on every iteration.

6. Run the script using Bash:

$ bash loop-out-functions.sh 

Output:

Hello, John! Hello, Doe! Hello, Admin! Hello, Jane! Hello, root! 

8. Use Functions with Conditional Statements

Bash functions can use conditional statements such as if, elif, if-then, and case inside or outside the function body to run specific commands.

1. Create a new if-elif-in-function.sh script:

$ nano if-elif-in-function.sh 

2. Add the following contents to the if-elif-in-function.sh file:

#!/bin/bash function count() { read var if (( var > 0 )); then echo "$var is greater than zero." elif (( var < 0 )); then echo "$var is less than zero." else echo "$var is zero." fi } count 

Save and close the file. The count function reads a value into the local var variable and uses an if-elif statement to check whether it's greater than, less than, or equal to zero.

3. Run the script using Bash:

$ bash if-elif-in-function.sh 

Enter a value such as 1 and verify the output:

1 1 is greater than zero. 

4. Create a new case-out-function.sh script:

$ nano case-out-function.sh 

5. Add the following contents to the case-out-function.sh file:

#!/bin/bash function help_page() { echo "Available options:" echo "1. apache" echo "2. mysql" echo "3. php" echo "Please enter a valid command or enter 'help' to view this page" } read -p "Enter a command (apache, mysql, php or help): " user_input case "$user_input" in apache) echo "Use dnf install httpd to install the Apache Web server..." ;; mysql) echo "Use dnf install mysql to install the MySQL database..." ;; php) echo "Use dnf install php to install PHP..." ;; help | -h) help_page ;; *) help_page ;; esac 

Save and close the file. The script calls the help_page function from the case statement whenever the user's input doesn't match any of the listed patterns.

6. Run the script using Bash:

$ bash case-out-function.sh 

Enter help when prompted to match the function's pattern:

Enter a command (apache, mysql, php or help): help Available options: 1. apache 2. mysql 3. php Please enter a valid command or enter 'help' to view this page 

Next Steps

  • Combine functions with arrays to process dynamic lists of arguments.
  • Build a small command-line tool that uses functions, variables, and loops together.
  • Explore Bash conditional statements in more depth to control function behavior.
  • Add error handling with custom exit codes to make your functions more robust.

For the full guide with additional tips, visit the original article on Vultr Docs.