Bash Functions

Function declaration, local variables, return codes, argument handling, and function libraries.

Overview

Overview Bash functions allow code reuse and organization within scripts. They behave like mini-scripts within your script, with their own positional parameters but sharing the script's variable scope by default.

Declaration syntax: Two equivalent forms exist: function name { body; } and name() { body; }. The name() form is slightly more POSIX-compatible. Functions must be defined before they are called (bash is interpreted top-to-bottom).

local keyword: Critical for preventing variable pollution. Without local, any variable set inside a function is global within the script. local var=value creates a variable that only exists within the function and its children. Always use local for function-internal variables.

Arguments: Inside a function, $1 $2 $@ $# refer to the function's arguments, shadowing the script's positional params. $0 still refers to the script name.

Return values — the key concept: The return statement in bash only returns an exit code (0-255 integer). It cannot return strings or complex data. To "return" a string, use echo inside the function and capture with command substitution: result=$(my_function). For large data, write to a file or use a global variable (named explicitly, not local).

$FUNCNAME: An array containing the call stack. ${FUNCNAME[0]} is the current function, ${FUNCNAME[1]} is the caller. Useful for error messages: echo "Error in ${FUNCNAME[0]}: message" >&2.

Sourcing libraries: source /path/to/lib.sh or . /path/to/lib.sh loads functions and variables from another file into the current shell. Use this to build reusable function libraries. Source relative paths: source "$(dirname "$0")/lib.sh".

Key concepts

  • local keyword
  • return vs echo for values
  • $FUNCNAME array
  • Sourcing function libraries

Interview questions

  • How do you return a string value from a bash function? Why can't you use the return statement?
  • Explain the difference between local and global variables in bash functions with an example.

Sign up free to read the full topic

More Linux topics

Start free on Cariara · Coding problems · System design studio