Example 1: Backup Script
- Create a script that automatically backs up files or directories.
#!/bin/bash
SOURCE_DIR="/home/user/documents"
BACKUP_DIR="/home/user/backups"
mkdir -p $BACKUP_DIR
cp -r $SOURCE_DIR/* $BACKUP_DIR
echo "Backup completed successfully!"
- This script creates a backup of the documents directory into the backups directory.
- It uses the cp command to copy files and directories (-r for recursive).
- It checks and creates the backup directory (mkdir -p).
Example 2: System Monitoring Script
- Create a script to monitor CPU and memory usage.
#!/bin/bash
echo "CPU Usage:"
top -n 1 | grep "Cpu(s)" | awk '{print $2 + $4 "% CPU used"}'
echo "Memory Usage:"
free -h | grep Mem | awk '{print $3 "/" $2 " used"}'
echo "Disk Space Usage:"
df -h | grep "^/dev/"
- top: To check CPU usage.
- free: To check memory usage.
- df: To check disk usage.
Example 3: Log Rotation Script
A log rotation script can help manage log files and prevent them from growing too large.
#!/bin/bash
LOG_DIR="/var/log/myapp"
MAX_SIZE=1048576 # 1MB in bytes
for log_file in $LOG_DIR/*.log; do
if [ $(stat -c %s "$log_file") -gt $MAX_SIZE ]; then
mv "$log_file" "$log_file.old"
echo "Archived $log_file"
fi
done
- This script checks all .log files in the specified directory.
- If a log file exceeds the size limit, it is renamed (archived) by adding .old.
Automating Scripts with Cron Jobs
- You can schedule your scripts to run automatically using Cron Jobs.
- This is especially useful for recurring tasks like backups, system monitoring, and log rotation.