31. Functions in Bash Scripts
Functions allow you to group a block of code and reuse it throughout your script, making the code cleaner, more modular, and easier to debug.
Defining a Function
There are two common ways to define a function:
- Standard:
function_name () { commands; } - Keyword:
function function_name { commands; }(The first style is often preferred).
bash #!/bin/bash
1. Define the function
create_project_folder () { read -p "Enter folder name: " FOLDER_NAME
if [ -d "$FOLDER_NAME" ]; then
echo "Error: Folder already exists."
return 1
fi
mkdir "$FOLDER_NAME"
echo "Folder $FOLDER_NAME created successfully."
}
2. Call the function
create_project_folder
Function Arguments
Functions accept arguments passed at the time of calling. Inside the function:
$1,$2, etc., refer to the first, second arguments.$#is the total number of arguments.$*or$@is the full list of arguments.
Example with Arguments:
bash check_status () { echo "Checking status for user: $1" # Check specific system status using $1 }
Calling the function:
check_status termux_user