Function Parameters and Returns
Passing Parameters to Bash Functions
Bash functions can accept parameters, which are passed as positional arguments. These arguments are referenced using special variables within the function.
Parameter Handling
Argument Variable |
Description |
$0 |
Script name |
$1, $2, $3 |
First, second, third arguments |
$@ |
All arguments as a list |
$## |
Total number of arguments |
Parameter Usage Example
## Function to greet with custom name
welcome() {
local name=$1
local age=${2:-unknown}
echo "Hello, $name!"
echo "Your age is: $age"
}
## Calling the function
welcome "John" 30
welcome "Alice"
Return Values and Exit Status
graph TD
A[Function Execution] --> B{Return Value}
B -->|Explicit Return| C[Return Integer]
B -->|Implicit Return| D[Last Command Exit Status]
Return Mechanisms
## Function with explicit return
calculate_sum() {
local result=$((${1} + ${2}))
return $result
}
## Function with exit status
validate_input() {
[[ -n "$1" ]] && return 0
return 1
}
## Usage examples
calculate_sum 5 7
sum_result=$?
echo "Sum: $sum_result"
validate_input "test"
if [[ $? -eq 0 ]]; then
echo "Input is valid"
fi
Local Variables and Scope
Local variables are crucial for maintaining function-level scope and preventing unintended modifications to global variables.
## Demonstrating variable scope
global_var="Global"
modify_vars() {
local local_var="Local"
global_var="Modified Global"
echo "Inside function: $local_var, $global_var"
}
modify_vars
echo "Outside function: $local_var, $global_var"