Functions & Practical Examples
Functions help you organize your scripts into reusable blocks of code.
1. Defining Functions
Functions can take arguments just like scripts, using $1, $2, etc.
#!/bin/bash
# Define function
greet_user() {
echo "Hello, $1! Welcome to the server."
}
# Call function
greet_user "John"2. Practical Automation: Log Backup
Here is a script that combines everything: variables, conditionals, and functions.
#!/bin/bash
LOG_DIR="/var/log/myapp"
BACKUP_DIR="/tmp/backups"
DATE=$(date +%Y-%m-%d)
# Function to check directory
ensure_dir() {
if [[ ! -d "$1" ]]; then
echo "Creating $1..."
mkdir -p "$1"
fi
}
echo "--- Starting Backup ---"
ensure_dir "$BACKUP_DIR"
if ls "$LOG_DIR"/*.log 1> /dev/null 2>&1; then
tar -czf "$BACKUP_DIR/logs-$DATE.tar.gz" "$LOG_DIR"/*.log
echo "Backup successful: logs-$DATE.tar.gz"
else
echo "No logs found to backup."
fi3. Setting Up Your Script
To run your script professionally:
- Add Shebang: Ensure
#!/bin/bashis at the top. - Permissions:
chmod +x script.sh. - Run:
./script.sh.
DevOps Automation Checklist
- Does the script have a shebang?
- Are variables quoted?
- Is there basic error checking (e.g., checking if a file exists)?
- Is the output clear for the user?
[!IMPORTANT] Exit Codes Use
exit 0for success andexit 1(or higher) for failures. This allows other scripts or CI/CD pipelines to know if your script succeeded.