Chapter 6.4 - Functions and Cron
Learning Objectives
By the end of this chapter, you will be able to:
- Create and use Bash functions
- Understand function parameters
- Schedule tasks with cron
- Use crontab
- Understand cron syntax
Bash Functions
Definition
#!/bin/bash
# Syntax 1
function_name() {
commands
}
# Syntax 2
function function_name {
commands
}
# Syntax 3 (portable)
function function_name() {
commands
}
Simple Example
#!/bin/bash
# Simple function
hello() {
echo "Hello $1!"
}
# Call
hello "Linux"
hello "World"
Parameters
#!/bin/bash
# Parameters: $1, $2, etc. (local to the function)
my_function() {
echo "First: $1"
echo "Second: $2"
echo "All: $@"
echo "Count: $#"
}
# Call
my_function "arg1" "arg2" "arg3"
Return Value
#!/bin/bash
# Return code (0-255)
is_file() {
if [ -f "$1" ]; then
return 0 # Success
else
return 1 # Failure
fi
}
# Usage
if is_file "/etc/passwd"; then
echo "File exists"
fi
Local Variables
#!/bin/bash
# Local variable (function scope)
my_function() {
local local_var="value"
echo "Local: $local_var"
}
# Global variable
global_var="global"
my_function
echo "Global: $global_var"
Function Examples
Utility Function
#!/bin/bash
# Logger with timestamp
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}
# Usage
log "Script start"
log "Error: File not found"
log "Script end"
Verification Function
#!/bin/bash
# Check if user exists
user_exists() {
id "$1" &>/dev/null
return $?
}
# Usage
if user_exists "user1"; then
echo "User exists"
else
echo "User does not exist"
fi
Function with Return Value
#!/bin/bash
# Return a value (via echo)
calculate() {
local result=$(( $1 + $2 ))
echo "$result"
}
# Usage
sum=$(calculate 5 3)
echo "Sum: $sum"
Cron - Task Scheduling
What is Cron?
Cron is a daemon that executes tasks at scheduled times.
Cron Syntax
Format
┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 7) (0 or 7 = Sunday)
│ │ │ │ │
* * * * * command
Examples
| Schedule | Description |
|---|---|
0 2 * * * | Every day at 2:00 AM |
*/5 * * * * | Every 5 minutes |
0 */2 * * * | Every 2 hours |
0 0 * * 0 | Every Sunday at midnight |
0 0 1 * * | The 1st of every month |
0 9-17 * * 1-5 | 9 AM to 5 PM, Monday-Friday |
0 0,12 * * * | Midnight and noon every day |
*/30 * * * * | Every 30 minutes |
Environment Variables
# In crontab
PATH=/usr/bin:/bin
SHELL=/bin/bash
MAILTO=admin@example.com
HOME=/home/user
# Then the tasks
0 2 * * * /path/to/script.sh
Using crontab
Edit Crontab
# Edit user crontab
crontab -e
# View current crontab
crontab -l
# Delete crontab
crontab -r
# Edit a user's crontab (root)
sudo crontab -u user1 -e
Crontab Format
# Comment
# MIN HOUR DAY MONTH DAY_OF_WEEK COMMAND
# Example
0 2 * * * /usr/local/bin/backup.sh
*/15 * * * * /usr/local/bin/check.sh
0 0 1 * * /usr/local/bin/monthly-report.sh
Redirection
# Redirect output
0 2 * * * /script.sh > /var/log/script.log 2>&1
# Ignore output
0 2 * * * /script.sh > /dev/null 2>&1
# Send by email (if MAILTO defined)
0 2 * * * /script.sh
Cron Directories
/etc/cron.d/
For system tasks:
# Create file in /etc/cron.d/
sudo nano /etc/cron.d/my-task
# Format (with user)
0 2 * * * user1 /usr/local/bin/script.sh
Special Directories
/etc/cron.hourly/ # Executed every hour
/etc/cron.daily/ # Executed every day
/etc/cron.weekly/ # Executed every week
/etc/cron.monthly/ # Executed every month
Place scripts in these directories (executable, without .sh extension)
Practical Examples
Daily Backup
#!/bin/bash
# /usr/local/bin/backup-daily.sh
BACKUP_DIR="/backup"
SOURCE_DIR="/data"
DATE=$(date +%Y%m%d)
tar -czf "$BACKUP_DIR/backup-$DATE.tar.gz" "$SOURCE_DIR"
find "$BACKUP_DIR" -name "backup-*.tar.gz" -mtime +7 -delete
Crontab:
0 2 * * * /usr/local/bin/backup-daily.sh
Log Cleanup
#!/bin/bash
# /usr/local/bin/cleanup-logs.sh
find /var/log -name "*.log" -mtime +30 -delete
find /var/log -name "*.gz" -mtime +90 -delete
Crontab:
0 3 * * 0 /usr/local/bin/cleanup-logs.sh
Monitoring
#!/bin/bash
# /usr/local/bin/check-disk.sh
THRESHOLD=80
USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$USAGE" -gt "$THRESHOLD" ]; then
echo "Alert: Disk at ${USAGE}%" | mail -s "Disk Alert" admin@example.com
fi
Crontab:
*/15 * * * * /usr/local/bin/check-disk.sh
Best Practices
Cron Scripts
#!/bin/bash
# 1. Shebang
# 2. Environment variables
PATH=/usr/bin:/bin
# 3. Script variables
LOG_FILE="/var/log/my-script.log"
# 4. Functions
# 5. Main code with logging
Logging
#!/bin/bash
LOG_FILE="/var/log/my-script.log"
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE"
}
log "Start"
# ... processing ...
log "End"
Error Handling
#!/bin/bash
set -euo pipefail
# Or manual handling
if ! command; then
echo "Error" | mail -s "Script Error" admin@example.com
exit 1
fi
Summary
In this chapter, you learned:
Functions: Definition, parameters, return values
Cron: Automatic task scheduling
Syntax: * * * * * (minute hour day month day_of_week)
crontab: Editing, viewing, deleting
Directories: /etc/cron.d/, cron.hourly, etc.
Practice: Scripts with logging, error handling
Next Steps
Module 7: Networking and Configuration
Module 8: Services and Daemons (with advanced crons)
Chapter created on: December 2024