TL;DR
This guide explains how to define, call, and modify Bash functions. We’ll cover passing arguments, returning values, using local variables, and understanding function scope.
Defining a Function
- Basic Syntax: Functions are defined using the
functionkeyword (optional) followed by the function name, parentheses for parameters, and curly braces containing the function’s code.function my_function { echo "Hello from my_function!" } - Calling a Function: Simply use the function name followed by any required arguments.
my_function
Passing Arguments to Functions
- Positional Parameters: Arguments are accessed using
$1,$2, etc., where$1is the first argument,$2the second, and so on.function greet { echo "Hello, $1!" }greet JohnOutput:
Hello, John! - Number of Arguments: The
$#variable holds the number of arguments passed to the function.function count_args { echo "You provided $# arguments." }count_args one two threeOutput:
You provided 3 arguments. - All Arguments: The
$@variable represents all the arguments passed to the function as a single string.function print_all { echo "Arguments: $@" }print_all one two threeOutput:
Arguments: one two three
Returning Values from Functions
- Using
echo: The most common way to return a value is by using theechocommand. Capture the output of the function into a variable.function add { local sum=$(( $1 + $2 )) echo "$sum" }result=$(add 5 3)echo "The sum is: $result"Output:
The sum is: 8 - Using the
returnstatement: Thereturnstatement exits the function and sets its exit status. This is useful for indicating success or failure, but can only return integer values (0-255).function check_positive { if (( $1 > 0 )); then return 0 # Success else return 1 # Failure fi }check_positive -5echo "Exit status: $?"Output:
Exit status: 1(because -5 is not positive)
Local Variables
- Scope: By default, variables declared inside a function have global scope. This means they can overwrite variables with the same name outside the function.
- Using
local: Use thelocalkeyword to declare variables that are only visible within the function’s scope.function my_func { local x=10 echo "Inside function: $x" }x=20my_funcecho "Outside function: $x"Output:
Inside function: 10
Outside function: 20(the global variable x remains unchanged)
Function Scope and Recursion
- Scope Rules: Variables declared with
localare only accessible within the current function’s execution context, including any functions it calls. This is crucial for avoiding unintended side effects. - Recursion Example: Functions can call themselves (recursion). Ensure a base case to prevent infinite loops.
function factorial { local n=$1 if (( $n <= 1 )); then echo 1 else echo $(( $n * $(factorial $(( $n - 1 ))))) fi }echo "Factorial of 5: $(factorial 5)"Output:
Factorial of 5: 120