Bash Functions
Bash functions bundle reusable logic under a name, accept positional arguments, and communicate results through exit status or output.
Defining a Function
A function is defined with the function keyword and a name, or more portably with just name() { ... }. The body is a block of commands between braces, and the function must be defined before it is called anywhere in the script.
Example
#!/bin/bash
function greet() {
echo "Hello from a function!"
}
greet
greetPositional Parameters: $1, $2, and $@
Arguments passed to a function are available inside it as $1, $2, and so on, exactly like command-line arguments to a script. $# holds the count of arguments, and $@ expands to all of them as separate words. These parameters are local to the function call and do not affect the script's own $1, $2 outside it.
Example
#!/bin/bash
introduce() {
echo "Name: $1"
echo "Role: $2"
echo "Total arguments: $#"
}
introduce "Sam" "Engineer"Returning Values
The return statement sets a function's exit status, a number from 0 to 255, and is meant for signaling success or failure -- 0 means success, anything else means an error. To return actual data like a string or number, print it with echo and capture it in the caller using command substitution $(function_name).
- return sets the exit status (0-255), checked with $? or in an if condition
- echo plus command substitution passes back computed data, e.g. result=$(add 2 3)
- local varname=value keeps a variable scoped to the function only
- Functions must be defined before they are called in the script
Example
#!/bin/bash
add() {
local sum=$(( $1 + $2 ))
echo "$sum"
}
is_even() {
if [ $(( $1 % 2 )) -eq 0 ]; then
return 0
else
return 1
fi
}
result=$(add 4 7)
echo "Sum: $result"
if is_even 6; then
echo "6 is even"
fiExercise: Bash Functions
Which of these is valid syntax for defining a Bash function named `greet`?