Get a Pentest and security assessment of your IT network.

Cyber Security

Bash Functions: A Practical Guide

TL;DR

This guide explains how to define, call, and modify Bash functions. We’ll cover passing arguments, returning values, using local variables, and understanding function scope.

Defining a Function

  1. Basic Syntax: Functions are defined using the function keyword (optional) followed by the function name, parentheses for parameters, and curly braces containing the function’s code.
    function my_function {
      echo "Hello from my_function!"
    }
  2. Calling a Function: Simply use the function name followed by any required arguments.
    my_function

Passing Arguments to Functions

  1. Positional Parameters: Arguments are accessed using $1, $2, etc., where $1 is the first argument, $2 the second, and so on.
    function greet {
      echo "Hello, $1!"
    }
    greet John

    Output: Hello, John!

  2. Number of Arguments: The $# variable holds the number of arguments passed to the function.
    function count_args {
      echo "You provided $# arguments."
    }
    count_args one two three

    Output: You provided 3 arguments.

  3. All Arguments: The $@ variable represents all the arguments passed to the function as a single string.
    function print_all {
      echo "Arguments: $@"
    }
    print_all one two three

    Output: Arguments: one two three

Returning Values from Functions

  1. Using echo: The most common way to return a value is by using the echo command. Capture the output of the function into a variable.
    function add {
      local sum=$(( $1 + $2 ))
      echo "$sum"
    }
    result=$(add 5 3)
    echo "The sum is: $result"

    Output: The sum is: 8

  2. Using the return statement: The return statement exits the function and sets its exit status. This is useful for indicating success or failure, but can only return integer values (0-255).
    function check_positive {
      if (( $1 > 0 )); then
        return 0 # Success
      else
        return 1 # Failure
      fi
    }
    check_positive -5
    echo "Exit status: $?"

    Output: Exit status: 1 (because -5 is not positive)

Local Variables

  1. Scope: By default, variables declared inside a function have global scope. This means they can overwrite variables with the same name outside the function.
  2. Using local: Use the local keyword to declare variables that are only visible within the function’s scope.
    function my_func {
      local x=10
      echo "Inside function: $x"
    }
    x=20
    my_func
    echo "Outside function: $x"

    Output:
    Inside function: 10
    Outside function: 20 (the global variable x remains unchanged)

Function Scope and Recursion

  1. Scope Rules: Variables declared with local are only accessible within the current function’s execution context, including any functions it calls. This is crucial for avoiding unintended side effects.
  2. Recursion Example: Functions can call themselves (recursion). Ensure a base case to prevent infinite loops.
    function factorial {
      local n=$1
      if (( $n <= 1 )); then
        echo 1
      else
        echo $(( $n * $(factorial $(( $n - 1 )))))
      fi
    }
    echo "Factorial of 5: $(factorial 5)"

    Output: Factorial of 5: 120

Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation