Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Linux

Bash functions with arguments, return values and scope

Write Bash functions that behave: passing arguments, returning data versus exit codes, local variables, cleanup with trap and reusable function libraries.

CloudSat teamNovember 18, 20268 min read
Interlocking puzzle pieces made of glowing lines of code, snapping together into a single tool.
On this pageDefining and calling a function

A Bash function is a named group of commands that runs in the current shell: no new process, the same variables, the same working directory. That makes functions fast and convenient, and it also explains every surprise they cause. This guide covers the parts that trip people up in real scripts: arguments, returning data, variable scope, error handling and sharing functions between scripts. The examples work in Bash 4.3 and later, except one section on a feature added in Bash 5.3, released in July 2025.

Defining and calling a function

greet() {
  echo "Hello, $1"
}

greet world      # prints: Hello, world

Bash accepts two syntaxes: name() { ...; }, which is POSIX and also works in sh, and function name { ...; }, which comes from ksh. Prefer the first. The braces are reserved words, so they need spaces around them, and a one-line function needs a semicolon before the closing brace: hi() { echo hi; }.

A function must be defined before the line that calls it runs. Longer scripts therefore define everything first and call a main function on the last line, which also gives the script a readable entry point:

main() {
  parse_args "$@"
  run_backup
}

main "$@"

Arguments

Inside a function, $1, $2 and so on are the function's own arguments, not the script's. $# is how many there are, "$@" expands to all of them as separate words, and shift drops the first one. Parameter expansion handles defaults and required values neatly:

DEFAULT_PORT=8080

serve() {
  local dir=${1:?usage: serve DIR [PORT]}
  local port=${2:-$DEFAULT_PORT}
  echo "serving $dir on port $port"
}

serve /srv/site         # serving /srv/site on port 8080
serve /srv/site 9000    # serving /srv/site on port 9000
serve                   # stops with: usage: serve DIR [PORT]

:- substitutes a default when the argument is missing or empty; :? prints the message and stops the script. Always pass arguments on as "$@" with the quotes. Without them, an argument that contains a space arrives as two arguments.

A function can also wrap a whole command line, which is a clean way to add behavior around existing tools:

quiet() {
  "$@" >/dev/null 2>&1
}

quiet apt-get update || echo "update failed"

If a function parses options with getopts, add local OPTIND at its top. getopts keeps its position in the global OPTIND, so a second call would otherwise skip the options.

Returning values: status versus output

return N ends the function with an exit status from 0 to 255, and callers test it with if or && like any command. The status is meant for success and failure, not data: values wrap around, so return 256 returns 0. To hand back data, print it and capture the output:

latest_backup() {
  ls -1t /var/backups/*.tar.gz 2>/dev/null | head -n 1
}

if file=$(latest_backup) && [[ -n $file ]]; then
  echo "newest backup: $file"
fi

$( ) runs the function in a subshell, so any variable it changes is lost when it returns. When a function must set a variable for the caller, a nameref (local -n) points at a variable whose name you pass in:

disk_use() {
  local -n out=$1
  out=$(df --output=pcent / | tail -n 1 | tr -dc '0-9')
}

disk_use ROOT_USE
echo "root is $ROOT_USE% full"

New in Bash 5.3: capture output without a subshell

Bash 5.3 added a form of command substitution that runs in the current shell, so side effects survive:

calls=0
next_id() { calls=$(( calls + 1 )); echo "id-$calls"; }

a=$(next_id)      # subshell: calls stays 0 out here
b=${ next_id; }   # Bash 5.3: same shell, calls becomes 1
echo "$a $b $calls"   # id-1 id-1 1

A sibling form, ${| command; }, expands to whatever the command leaves in the REPLY variable instead of its output. Older versions stop with "bad substitution", so check echo "$BASH_VERSION" before relying on either form.

Scope: global unless you say local

Variables assigned inside a function are global by default. This innocent helper overwrites any total the caller had:

count_lines() {
  total=0
  for f in "$@"; do
    total=$(( total + $(wc -l < "$f") ))
  done
  echo "$total"
}

Declare working variables with local (local total=0) and the problem disappears. Bash scoping is dynamic: a local variable is also visible to every function called from inside that function.

outer() { local mode=dry-run; inner; }
inner() { echo "inner sees mode=$mode"; }

outer    # inner sees mode=dry-run

One trap deserves its own line. local result=$(some_command) always succeeds, because the exit status you see is that of local, not of the command. Declare first and assign second (local result then result=$(some_command)) whenever you test the status. When a function should set a global on purpose, declare -g NAME=value makes the intent explicit.

Errors and cleanup

die() { echo "error: $*" >&2; exit 1; }

workdir=$(mktemp -d) || die "cannot create a temporary directory"
cleanup() { rm -rf "$workdir"; }
trap cleanup EXIT

cp /etc/nginx/nginx.conf "$workdir/" || die "copy failed"

trap cleanup EXIT runs the cleanup function however the script ends: normally, through die, or after an interrupt with Ctrl+C. Temporary files then never pile up.

set -e has a blind spot with functions. When a function is called as an if condition or inside a && or || list, errexit is switched off for its entire body:

set -e
deploy() { false; echo "still running"; }
if deploy; then echo "deploy reported success"; fi

Both lines print, because the failing false no longer stops anything. Check important steps explicitly with || return 1 inside the function instead of trusting set -e.

For useful error messages, the FUNCNAME array holds the call stack: log() { echo "[${FUNCNAME[1]}] $*" >&2; } prefixes each message with the name of the function that logged it.

Sharing functions between scripts

Keep common helpers in one file and load it with source (or its short form, .), which runs the file in the current shell:

[[ -n ${COMMON_SH_LOADED:-} ]] && return
COMMON_SH_LOADED=1

log()  { printf '%s %s\n' "$(date '+%F %T')" "$*" >&2; }
die()  { log "error: $*"; exit 1; }
need() { command -v "$1" >/dev/null || die "missing command: $1"; }

The first two lines make loading the file twice harmless. Each script then starts with:

source "$(dirname "$0")/lib/common.sh"
need rsync
log "starting backup"

A few builtins help you manage what is loaded. declare -f name prints a function's definition, declare -F lists every function name, unset -f name removes one, and type name tells you whether a name is a function, an alias, a builtin or a file on disk.

export -f makes a function available to child Bash processes, which is how you use one with xargs or find:

compress_log() { gzip -9 "$1" && echo "compressed $1"; }
export -f compress_log
find /var/log/myapp -name '*.log.1' -print0 | xargs -0 -n 1 -P 4 bash -c 'compress_log "$1"' _

A practical example: retry with backoff

retry() {
  local attempts=$1 delay=$2 n=1
  shift 2
  until "$@"; do
    if (( n >= attempts )); then
      echo "gave up after $n attempts: $*" >&2
      return 1
    fi
    sleep "$delay"
    delay=$(( delay * 2 ))
    n=$(( n + 1 ))
  done
}

retry 5 2 curl -fsS -o /dev/null https://example.com/health

The command runs up to five times, waiting 2, 4, 8 and then 16 seconds between attempts. A helper like this earns its place in first-boot scripts, when the network or a package mirror may not be ready yet; on CloudSat you can attach such a startup script when you deploy a server.

Functions, aliases and scripts

Question Alias Function Script file
Takes arguments only appended at the end yes, as $1, $2... yes
Runs in the current shell the current shell a new process
Can change your shell (cd, variables) yes yes no
Usable from other scripts no when sourced or exported yes
Best for short shortcuts logic in a shell or script standalone tools

FAQ

Why did my function change a variable it should not touch?

Every variable assigned in a function is global unless you declare it with local. Make local the first line of each function for all of its working variables, and the leaks stop.

Can a Bash function return a string?

Not through return, which only carries a number from 0 to 255. Print the string and capture it with result=$(my_function), or pass the name of a variable and fill it through a nameref.

How do I debug a function that misbehaves?

Turn on tracing around the call with set -x and off again with set +x, or run the whole script with bash -x script.sh. Each traced line starts with the value of PS4, so setting PS4='+ ${FUNCNAME[0]:-main}:$LINENO: ' first makes every line show the function and line number it came from. ShellCheck catches most scope and quoting mistakes before you ever run the script.

Where should I keep functions I use every day?

Interactive helpers belong in ~/.bashrc, or in a separate file that it sources so the file stays tidy. Functions shared by scripts belong in a library file under version control, loaded with source at the top of each script.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.