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.
#!/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.
$ 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.
$ bash function-demo.sh INFO: found file: input.txt ERROR: missing file: missing.txt WARN: continuing after check
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.