Skip to main content

Functions

Functions in Bash are named blocks of shell commands. Bash executes the block in the current shell environment when we call the function. Two common ways to define them:
Both work in Bash. The second form is also portable to POSIX-compatible shells, while the function keyword is Bash-specific. We call a function just by its name: my_func.

Local Variables

Assignments inside a function affect global variables by default. If we want a variable local to the function call, we use the local keyword:
The local var temporarily hides the global var, so changing it does not change the global value. Bash uses dynamic scoping, which means functions called from my_func can also see this local variable while my_func is running.

Passing Parameters

We pass parameters to functions the same way as script arguments — they are accessed with $1, $2, etc. inside the function:

Return Values

Bash functions return an exit status from 0 to 255, not a general value like a C function. Some common statuses are: We set a function’s status with return N. Without an explicit return, the function uses the status of its last command. We access the most recent exit status with $?.

Debugging

This enables xtrace debugging. Can’t really write the whole debug output here lmao :D. Basically, Bash prints commands after expanding variables and other substitutions, just before it executes them. Really useful when a script is silently failing and we have no idea where. One warning: xtrace can expose passwords, tokens and other secrets contained in commands, so we should check the output before saving or sharing it.