Function arguments and return status
Each function call receives its own positional arguments: $1, $# and "$@" describe that call, and the caller’s positional arguments are restored afterward. Check the count before using required arguments. return n ends the function with an exit status, not a string or arbitrary number; use 0 for success and small nonzero values for failures. With no explicit return, the status is the last command executed. exit instead terminates the current shell environment, which is usually not what a reusable helper should do. Use stdout for data and stderr for diagnostics. Command substitution captures stdout, strips trailing newlines, and normally runs in a subshell environment in Bash 5.2; capture status using an assignment or an if condition. Declare locals separately from assignments containing command substitution, because local value=$(...) reports the status of local rather than reliably preserving the substitution status. Example 3 captures a failed substitution and prints its status for inspection; the final successful printf means inspect itself returns zero. If failure must propagate, explicitly return the saved status. A printf format containing one conversion may still print an empty field when no arguments are supplied; check the argument count to distinguish that from an actual empty argument.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Arguments belong to the call
set -- outershow() { printf 'count=%s\n' "$#" printf '[%s]\n' "$@"}show 'two words' ''printf 'caller=%s\n' "$1"Expected stdout:
count=2[two words][]caller=outerThe empty argument is preserved and the caller keeps outer.
Return a status
check() { if [[ $# -eq 1 && -n $1 ]]; then return 0; fi return 2}check goodprintf 'valid=%s\n' "$?"check ''printf 'invalid=%s\n' "$?"Expected stdout:
valid=0invalid=2The immediate status capture distinguishes valid and invalid input.
Capture data and status separately
produce() { printf 'data\n\n'; return 4; }inspect() { local value status value=$(produce) status=$? printf 'value=[%s] status=%s\n' "$value" "$status"}inspectExpected stdout:
value=[data] status=4The assignment reports substitution status; trailing newlines disappear.
Common mistakes
Do not use return to send a string, and do not print diagnostics to stdout when callers capture data. Avoid combining local and a substitution whose failure matters.
Practice
Write a function accepting exactly one nonempty argument. Print the argument on success; on invalid input write a diagnostic to stderr and return 2. Test no arguments, an empty argument and a phrase with spaces.
Next: Local variables and dynamic scope