Mastering System Automation: Practical Scripts for Everyday Tasks — Part 2
Introduction
Automation is the key to efficiency. Whether you’re managing a personal server or a large-scale infrastructure, automating repetitive tasks can save time, reduce errors, and improve consistency. In the previous installment, we covered the basics of scripting for system administration. In this follow-up post, we dive deeper into practical scripts that automate system tasks — making your Linux environment smarter and easier to manage.
In this guide, we’ll explore scripts that handle backups, system monitoring, log rotation, and even automate tasks with cron jobs. Ready to supercharge your system automation skills? Let’s get started!
1. Backup Script: Protecting Your Data
Data loss can be catastrophic, but with a simple backup script, you can safeguard important files with minimal effort. Automating backups ensures that your data is consistently protected, without the need for manual intervention.
How It Works
The script below copies files from a source directory to a backup directory. If the backup directory doesn’t exist, it creates it. Then, it performs a copy operation using cp -r
to include all files and subdirectories.
#!/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!"
Why It’s Useful
mkdir -p
ensures the backup directory exists, creating it if necessary.cp -r
recursively copies files and subdirectories.- The script outputs a message when the task is complete.
With this script in place, your files are backed up automatically with no need for manual copying. You can also customize the source and destination directories to fit your needs.
2. System Monitoring Script: Keep Your System Healthy
Monitoring system resources like CPU usage, memory consumption, and disk space is critical for maintaining optimal performance. A simple script can check these metrics and alert you if something goes wrong.
How It Works
This script uses common Linux commands like top
, free
, and df
to fetch system statistics. It then outputs the results in a user-friendly format.
#!/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/"
Why It’s Useful
top -n 1
provides a one-time snapshot of CPU usage.free -h
gives a human-readable format for memory usage.df -h
reports disk space usage, ensuring you don’t run out of storage.
This script is an excellent starting point for any system administrator who wants to keep track of system resources.
3. Log Rotation Script: Prevent Log Files from Overgrowing
Log files can quickly become bloated and eat up valuable disk space if not managed properly. A log rotation script can help you archive older logs and keep things tidy.
How It Works
This script checks the size of each .log
file in a specified directory. If a file exceeds the defined size limit, it renames the file by appending .old
to it and moves on to the next one.
#!/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
Why It’s Useful
stat -c %s
retrieves the file size, which is then compared to the maximum allowed size.- If the file exceeds the limit, it’s archived with a
.old
suffix. - This prevents your log files from growing uncontrollably.
4. Automating with Cron Jobs: Make Your Scripts Run Automatically
Once your scripts are ready, you’ll want them to run automatically on a schedule. That’s where cron jobs come in. Cron allows you to schedule scripts to run at specified intervals — whether daily, weekly, or monthly.
How It Works
You can set up a cron job to run your backup or system monitoring scripts at specific times. Cron uses a simple syntax to define the schedule.
For example, to run a script every day at 2:00 AM, add the following line to your crontab:
0 2 * * * /home/user/scripts/backup.sh
Cron Syntax Breakdown:
- Minute (0–59)
- Hour (0–23)
- Day of the month (1–31)
- Month (1–12)
- Day of the week (0–6, where Sunday = 0)
With cron jobs, you can automate your scripts to handle tasks like backups or monitoring without needing to intervene.
Practical Exercises: Sharpen Your Scripting Skills
Now that you’ve seen some practical examples, it’s time to try your hand at writing your own scripts. Here are a few exercises to test your skills:
- Script to Greet the User and Calculate Years Until They Turn 100:
Write a script that prompts the user for their name and age, then outputs a greeting and calculates how many years are left until they turn 100. - Directory Check Script:
Write a script that checks if a directory exists. If it doesn’t, create it. - Disk Usage Warning Script:
Write a script that monitors disk usage and sends a warning email if the disk usage exceeds a certain threshold (e.g., 90%). - Service Health Check Script:
Automate a system task, like checking the availability of a service (e.g.,systemctl status nginx
) and restarting it if it’s down. - Log Rotation Script for Deleting Old Logs:
Write a script that deletes logs older than 30 days from a specified directory.
Conclusion: Unlock the Power of Automation
By creating and automating these simple yet powerful scripts, you’ll have a much more efficient and reliable system. Automation helps you stay ahead of potential issues and minimizes the need for manual intervention. Whether it’s for backup management, system monitoring, or log maintenance, scripts can be your best ally in keeping your system running smoothly.
Want to keep up with future updates and scripts? Stay tuned for more tutorials and automation tips by following us on Twitter.
For a deeper dive into cybersecurity and system administration, check out our full guide on Notion.
Feel free to explore our GitHub repository for more scripts and resources. Start automating today and make your Linux system smarter!