Reusable shell logic belongs in a Bash function when the same command sequence needs a name, arguments, and a return status the caller can test. A small function keeps logging, path checks, cleanup hooks, and wrapper commands in one place instead of duplicating fragile blocks through a script.

Bash gives each function its own positional parameters, so $1 inside the function is the first argument passed to the function call, not necessarily the script's first argument. Variables declared with local stay inside the current function, which prevents helper names from overwriting values used by the caller.

A logging helper and a file check show argument handling, local variables, and return status without adding a larger script. Syntax is parsed with bash -n, the found-file branch prints INFO, and the missing-file branch returns status 1 so the caller can decide whether to continue.

Steps to create a function in Bash:

  1. Create a script with two named functions and a caller that handles a failed check.
    function-demo.sh
    #!/usr/bin/env bash
    set -euo pipefail
     
    log_message() {
        local level=$1
        local message=$2
        printf "%s: %s\n" "$level" "$message"
    }
     
    require_file() {
        local path=$1
        if [ ! -f "$path" ]; then
            log_message ERROR "missing file: $path"
            return 1
        fi
        log_message INFO "found file: $path"
    }
     
    printf "demo\n" > input.txt
    require_file input.txt
    require_file missing.txt || log_message WARN "continuing after check"

    Use local for variables that belong only inside a function. Bash removes those names when the function returns.

  2. Check the script syntax before running it.
    $ bash -n function-demo.sh

    No output means Bash did not find a syntax error. It does not prove that the files checked by the script exist at runtime.

  3. Run the script and verify that both function paths execute.
    $ bash function-demo.sh
    INFO: found file: input.txt
    ERROR: missing file: missing.txt
    WARN: continuing after check
  4. Use the function return status where the caller needs to decide whether to continue.
    require_file missing.txt || log_message WARN "continuing after check"

    The || branch runs only when require_file returns a nonzero status. In this script, return 1 from the missing-file branch triggers the warning call.