Functions in Bash

A function is a named block of code that performs a specific task. Instead of writing the same code in multiple places, define it once as a function and call it wherever needed. Functions make scripts shorter, cleaner, and easier to maintain.

Defining a Function

There are two ways to define a function in Bash. Both work identically.

Style 1 – With the function keyword

function greet {
  echo "Hello from the greet function!"
}

Style 2 – Without the function keyword

greet() {
  echo "Hello from the greet function!"
}

Calling a Function

Write the function name to call it. The function must be defined before it is called.

#!/bin/bash
greet() {
  echo "Hello! Welcome to eStudy247."
}

greet

Output:

Hello! Welcome to eStudy247.

Function Flow Diagram

┌───────────────────────────────────────────────┐
│             Function Execution Flow           │
│                                               │
│  Script starts at top                         │
│         │                                     │
│  Define greet() ──────────────────────┐       │
│         │                             │       │
│  Call greet ──► Jump to function ──── ┘       │
│         │       Run function body             │
│         │       Return to caller              │
│  Continue rest of script                      │
└───────────────────────────────────────────────┘

Passing Arguments to a Function

Arguments are passed to a function just like passing arguments to a script. Inside the function, use $1, $2, etc., to access them.

#!/bin/bash
add_numbers() {
  result=$(( $1 + $2 ))
  echo "Sum of $1 and $2 is: $result"
}

add_numbers 8 12
add_numbers 100 250

Output:

Sum of 8 and 12 is: 20
Sum of 100 and 250 is: 350

Returning a Value from a Function

Bash functions do not return values the way most languages do. The return statement only returns a status code (0–255). To return an actual value, either use a global variable or command substitution.

Method 1 – Using a Global Variable

#!/bin/bash
multiply() {
  answer=$(( $1 * $2 ))
}

multiply 6 7
echo "Result: $answer"

Output:

Result: 42

Method 2 – Using Command Substitution

#!/bin/bash
square() {
  echo $(( $1 * $1 ))
}

result=$(square 9)
echo "Square of 9 is: $result"

Output:

Square of 9 is: 81

Return Status Code

The return statement exits the function and sets the exit code. By convention, 0 means success and any non-zero value means failure.

#!/bin/bash
check_age() {
  if [ $1 -ge 18 ]; then
    return 0   # success (eligible)
  else
    return 1   # failure (not eligible)
  fi
}

check_age 20
if [ $? -eq 0 ]; then
  echo "Eligible to apply."
else
  echo "Not eligible."
fi

Output:

Eligible to apply.

Local Variables in Functions

By default, all variables in Bash are global. To keep a variable confined to the function only, use the local keyword. This prevents accidental changes to variables in the main script.

#!/bin/bash
my_function() {
  local temp_name="Inside Function"
  echo "$temp_name"
}

my_function
echo "$temp_name"   # This prints nothing — variable is local

Output:

Inside Function

Global vs Local Variable Diagram

┌─────────────────────────────────────────────────┐
│                                                 │
│  SCRIPT SCOPE                                   │
│  ┌──────────────────────────────────────────┐   │
│  │  name="Alice"   ← Global, visible        │   │
│  │  everywhere                              │   │
│  │                                          │   │
│  │  FUNCTION SCOPE                          │   │
│  │  ┌────────────────────────────────────┐  │   │
│  │  │  local city="Delhi"  ← Only here   │  │   │
│  │  └────────────────────────────────────┘  │   │
│  └──────────────────────────────────────────┘   │
└─────────────────────────────────────────────────┘

Calling Functions Multiple Times

#!/bin/bash
print_line() {
  echo "-------------------------------"
}

print_line
echo "Report Title"
print_line
echo "Section One"
print_line

Output:

-------------------------------
Report Title
-------------------------------
Section One
-------------------------------

Recursive Functions

A recursive function calls itself. This is useful for calculations like factorial.

#!/bin/bash
factorial() {
  if [ $1 -le 1 ]; then
    echo 1
  else
    local sub=$(factorial $(( $1 - 1 )))
    echo $(( $1 * sub ))
  fi
}

result=$(factorial 5)
echo "Factorial of 5 is: $result"

Output:

Factorial of 5 is: 120

Practical Example – Server Status Check Function

#!/bin/bash
check_service() {
  service=$1
  if systemctl is-active --quiet $service; then
    echo "$service is RUNNING"
  else
    echo "$service is STOPPED"
  fi
}

check_service nginx
check_service mysql
check_service ssh

Key Takeaways

  • Functions prevent code repetition — define once, call anywhere.
  • Pass arguments using $1, $2, etc., inside the function.
  • Use local to keep variables inside the function scope.
  • Use command substitution $(function_name) to capture a function's output.
  • The return statement sends an exit status code, not a data value.
  • Define functions before calling them in the script.

Leave a Comment