BudiBadu Logo
Samplebadu

Bash by Example: Functions

Bash 5.0+

Defining and calling functions to organize code into reusable blocks, understanding function syntax variations between POSIX and Bash-specific styles, managing variable scope with local declarations, returning values via exit status, and implementing modular script design patterns.

Code

#!/bin/bash

# Define function
greet() {
    echo "Hello from function!"
}

# Alternative syntax with 'function' keyword
function farewell {
    echo "Goodbye!"
}

echo "Start"
greet
farewell
echo "End"

Explanation

Functions allow you to group commands into reusable blocks, improving script organization and readability. By defining a function once, you can call it multiple times throughout your script, reducing redundancy and making maintenance easier.

There are two common syntaxes for defining functions in Bash. The POSIX-compliant name() { ... } is generally preferred for portability across different shells. The Bash-specific function name { ... } is also valid but less portable. Key characteristics of functions include:

  • Global Scope: Variables defined inside functions are global by default.
  • Exit Status: Functions return the exit status of the last executed command.
  • No Parentheses: Functions are called by name without parentheses.

Functions execute in the current shell context, meaning they can modify global variables and environment settings. To avoid side effects, it is best practice to use local variables for internal data.

Code Breakdown

4
Defining a function named greet. The body is enclosed in curly braces {}. This is the most common and portable syntax.
9
Using the function keyword. This is explicit but specific to Bash and KornShell. It works identically to the previous syntax in Bash.
14
Calling the greet function. Notice there are no parentheses () used in the call, unlike in C or Python.
15
Calling the farewell function. The script executes the commands inside the function body and then returns to this point.