Bash: Functions
Functions allow you to group a set of commands to be reused multiple times throughout your script, making your code more organized and readable.
Defining a Function
Basic function syntax
function greet {
echo "Hello, world!"
}
The `function` keyword is optional, but it improves readability. The commands go between curly braces `{}`.
Calling a Function
Calling the function by name
greetTo run the function, simply call its name as you would a regular command.
Functions with Parameters
Passing parameters to a function
function greet_user {
echo "Hello, $1!"
}
greet_user "Alice"
Inside a function, parameters are accessed using `$1`, `$2`, etc., just like in a regular script.
Return Values
Returning a status code
function check_file {
if [ -f "$1" ]; then
return 0 # Success
else
return 1 # Failure
fi
}
check_file "my_file.txt"
if [ $? -eq 0 ]; then
echo "File exists."
fi
Functions use the `return` command to exit with a status code. A status of `0` typically means success, and a non-zero status means failure. The special variable `$?` holds the status code of the last executed command or function.
Since [] itself already returns success/failure, you can shorten the 'check_file' function:
function check_file { [ -f "$1" ]; }
check_file "my_file.txt"
if [ $? -eq 0 ]; then
echo "File exists."
fi