Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 95 ยท Shell Scripting

Functions

Write Bash functions: arguments, return versus exit, returning data via stdout, local variables, recursion, libraries with source, namerefs and composition.

Once a script grows past twenty lines, you start copying the same few commands into several places. A function gives a name to a block of commands so you can call it like any other command, with its own arguments, and change it in one place. Functions are also how you turn a long, top-to-bottom script into readable pieces: parse_args, check_prerequisites, main.

Bash functions behave like small scripts that run inside the current shell. That makes them fast, and it also means some things work differently from other languages: arguments are $1 $2 ..., a function "returns" only a small number, real results come out through standard output, and variables are global unless you say otherwise. In this lesson you will learn all of that, plus recursion, shared function libraries with source, and namerefs for passing variables by name.

Defining and calling a function

There are two equivalent ways to define a function; the first is the portable one and the one you should use:

TEXT
   name() { commands; }          POSIX form (use this)
   function name { commands; }   Bash form (also allowed: function name() { ...; })

Calling is just writing the name, followed by arguments, with no parentheses. Inside the function the arguments are available as the positional parameters $1, $2, ..., $# (the count), "$@" (all of them, each preserved) and $*. They belong to the function call; the script's own $1 is hidden for the duration (but $0 is still the script's name).

Bash Defining, calling and inspecting functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Take note of the following:

  • "$@" preserved the empty argument and the one with a space: four arguments in, four lines out. Always quote it.
  • A function must be defined before it is called, because Bash reads the script top to bottom. (A function may call another one defined later, as long as the call only happens after both exist.)
  • type greet prints the function body. declare -F lists function names, and declare -f name prints the code. unset -f name removes it.
  • A function and a command can have the same name; the function wins. Use command ls to bypass a function or alias and run the real program. Also pick names that do not collide with common commands.
  • The brace form requires a ; or newline before the closing }, as for command groups (Subshells, Groups and Environment). You can use ( ... ) instead of { ... } as the function body to run it in a subshell.

Returning results: status, stdout and variables

In most languages a function returns a value. In Bash there are three different mechanisms, and picking the right one is the key skill:

Mechanism What it carries How to use
return N Exit status 0 to 255 (success or failure) if my_func; then, `my_func
Output to stdout Any text (strings, numbers, lists) result=$(my_func)
A variable set by the function Anything, including arrays Read the variable afterwards

return takes a number from 0 to 255 and only exists to say "it worked" (0) or "it failed" (anything else). return without a number returns the status of the last command. If a function ends without return, its status is the status of its last command.

Bash return, command substitution and global variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

What this teaches:

  • A function whose last command is a test is itself a test. is_even is just (( ... )), so if is_even 4 works. This is the most elegant style for predicates: no output, only a status. Name them like questions (is_..., has_...).
  • return 300 wraps around to 44 (300 mod 256). Statuses are one byte.
  • Output is the way to return data: sum=$(add 3 4) captures everything the function wrote to stdout. The catch: anything else the function prints is captured too, so log messages and errors should go to stderr (echo "..." >&2). Capturing also costs a subshell (a fork), which matters inside tight loops.
  • For several values, print them on one line and split with read, or fill an array.
  • Setting a global variable is fast and needs no subshell: set_result changed result in the caller directly. But when the function is called inside $( ), it runs in a subshell and the change is lost (the after subshell line). Use this approach for performance-sensitive code, and document the variable name.

Local variables and scope

All variables in Bash are global by default, even those first created inside a function. The local keyword creates a variable that exists only during the function call (and in the functions it calls, because Bash uses dynamic scope).

Bash local versus global variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Four rules come out of it:

  1. Declare every function variable local (including loop counters), or you will overwrite a variable of the caller. leak shows how an assignment reaches outside, and even creates a new global (y).
  2. Dynamic scope: inner can see and change outer's local v, because it was called while outer was running. The caller's global v stayed top. Treat it as a feature to be careful with: functions should not depend on variables of their callers unless documented.
  3. local n=$(cmd) hides the exit status. The status of local itself (0) replaces the status of the substitution. Split it: local n; n=$(cmd). This matters under set -e and when you check $?. (ShellCheck warns about it as SC2155.)
  4. Using a global deliberately (like count) is fine for state shared by a family of functions, ideally with an upper-case or prefixed name.

Recursion

A function can call itself. Each call gets its own local variables, so recursion works naturally. Recursive functions in Bash are slow when the recursion goes through $( ), because each level forks a subshell. They are good for tree-shaped data and teaching, less so for hot loops.

Bash Recursive functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

countdown recurses without a subshell, so it prints as it goes and costs almost nothing. fib is the classic bad idea: each call spawns two subshells, so the work doubles at every level (fine for 10, painful for 25). Bash has no tail-call optimization; very deep recursion is limited by memory, so prefer a loop for large depths. For anything numeric and heavy, use awk.

Function libraries with source

Functions you reuse across scripts belong in a library file that scripts load with source file (or its shorthand . file). Sourcing runs the file's commands in the current shell, so all its functions and variables become available. A library has no shebang line and usually does not need execute permission.

Bash Writing and sourcing a function library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Details worth knowing:

  • Use a path with a slash (./lib.sh, or "$(dirname "$0")/lib.sh"). Without a slash, source also searches PATH, which is both surprising and a security risk.
  • die here calls log and sends the message to stderr (>&2), which appears separately in the output. In a script you would write exit 1 after reporting; inside a function that is called from a command substitution or a ||, think about whether you want to end the whole script or only return.
  • A separate script (bash run.sh) does not see your functions. They are not environment variables. export -f name puts the function into the environment so child Bash processes can use it. This is Bash-only, and a clean way to use a function with xargs -I{} bash -c 'log ...' or find -exec bash -c.
  • A common idiom is a guard so a library is not loaded twice: [[ -n ${_LIB_LOADED:-} ]] && return; _LIB_LOADED=1.
  • Libraries are the home for log, die, require_command and similar helpers; the later lessons on script design build on this.

Namerefs: passing variables by name

Because Bash cannot pass arrays or "references" to functions, the traditional trick is to pass the name of a variable and use indirection. Since Bash 4.3 there is a cleaner version, a nameref created with local -n (or declare -n). A nameref is an alias: reading or writing it reads or writes the variable it names.

Bash local -n namerefs, composition and defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

  • set_by_name target wrote into the caller's variable target, which did not even exist yet. The same trick fills an array (fill letters) and reads one (sum_array nums) without copying it. See Arrays and Associative Arrays.
  • Take care that the nameref's own name does not equal the variable you pass (a classic bug: local -n arr=$1 with a caller variable that is itself called arr).
  • Composition: small functions that each do one thing and write their result to stdout can be nested (slug calls upper) and combined with pipes. Name them clearly and keep them short.
  • ${1:-none} provides defaults for missing arguments (Parameter Expansion and String Handling). Validating arguments at the top of a function ((( $# == 2 )) || return 2) catches mistakes early.

Functions, exit and set -e

return ends the function, exit ends the shell that is running it (a subshell when you are inside ( ) or $( )). Be careful with set -e inside functions: when a function is used as a condition (if f, f || ..., f && ...), Bash disables -e inside it, so a failing command in the middle does not stop it.

Bash return, exit and set -e inside functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

fail printed its message even though false ran just before it: set -e was ignored because the call was part of an || list, and the function's final echo returned 0, so the || branch never ran. Test conditions and set -e interact in surprising ways, see Exit Codes, set -e and Error Handling. Also note that $0 inside a function is still the script's name (main.sh in our editor); the function name is in $FUNCNAME.

When to use functions

  • Use them for any block you repeat, for naming steps (main, usage, cleanup), for predicates (is_...), for log and die helpers, and for code you want to test in isolation.
  • Keep them small, with local variables, arguments instead of globals, results through stdout or a documented global, and status for success/failure.
  • Avoid functions that need ten parameters (use an associative array or a different tool), and capturing in $( ) inside tight loops when a global result variable would do.
  • If you start wanting objects, deep data structures, or unit tests everywhere, the problem may have outgrown Bash.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is the correct way to get a function's computed text into a variable?

    Functions return data through standard output, which command substitution captures. return only carries a status from 0 to 255, and $? is just that number.
  2. 2. What is the effect of local n=$(false) on $??

    The status of a local assignment is the status of local, not of the command substitution. Declare first (local n), then assign (n=$(cmd)).
  3. 3. A function runs x=5 without local. What happens?

    Bash variables are global unless declared local, so the assignment changes or creates a variable in the caller's scope.
  4. 4. What does return 300 produce as the status of a function?

    Exit statuses are one byte, so 300 wraps around to 300 - 256 = 44.
  5. 5. Why does bash script.sh not see a function you defined in your current shell?

    Functions live in the memory of the shell that defined them. Source the file in the new shell, or export -f the function for child Bash processes.

Summary

  • Define with name() { ...; }, call with name args; inside, use $1 ... $# and "$@". The function must exist before it is called.
  • Three ways to give results back: status with return N (0 to 255), text on stdout captured with $( ), or a (documented) global variable.
  • Variables are global by default. Declare every function variable local, and split local n; n=$(cmd) to keep the status.
  • Scope is dynamic: a called function sees the caller's locals.
  • Recursion works, but through $( ) it forks each level; prefer loops for big depths.
  • Put shared functions in a library and load it with source ./lib.sh; export -f shares a function with child Bash processes.
  • local -n name=$1 creates a nameref so a function can read or write a variable, or an array, chosen by the caller.
  • set -e is ignored inside a function used as a condition.

Next: Arrays and Associative Arrays