0Pricing
Linux Server Deployment & SSH Mastery · Lesson

Automating Server Tasks

Write scripts to automate common administrative tasks such as backups, log cleanup, service restarts, and system health checks.

Automating Server Tasks is a free Linux Server Deployment & SSH Mastery lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Linux Server Deployment & SSH Mastery learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Automating Server Tasks

Welcome to automating server tasks! As a developer or admin, you often perform repetitive actions. Bash scripts can automate these, saving time and reducing errors.

In this lesson, we'll learn how to script common tasks like backups, log cleanup, service restarts, and health checks.

Why Automate with Bash?

Automation is key for efficient server management. Here's why:

  • Consistency: Scripts perform tasks the same way every time.
  • Efficiency: Save time on repetitive manual work.
  • Error Reduction: Less human error means more reliable operations.
  • Scheduling: Easily run tasks at specific times using tools like cron (which we'll cover later).

Scripting Simple Backups

Regular backups are crucial. A simple Bash script can archive important directories and timestamp them for easy organization.

We often use the tar command to create compressed archive files (tarballs) of directories.

Backup Script Demo

This script creates a dummy directory, adds some files, then archives it into a timestamped .tar.gz file in a specified backup location. Run it to see how it works!

#!/bin/bash

BACKUP_DIR="/tmp/coddykit_backups"
SOURCE_DIR="/tmp/coddykit_data_to_backup"

# Create backup and source directories if they don't exist
mkdir -p "$BACKUP_DIR"
mkdir -p "$SOURCE_DIR"

# Create some dummy files to back up
echo "Content for file1" > "${SOURCE_DIR}/file1.txt"
echo "Content for file2" > "${SOURCE_DIR}/file2.txt"

# Generate a timestamp for the backup file
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/data_backup_${TIMESTAMP}.tar.gz"

echo "Creating backup of $SOURCE_DIR..."
# Create a compressed tar archive
tar -czf "$BACKUP_FILE" -C "${SOURCE_DIR}" .

echo "Backup created: $BACKUP_FILE"
echo "Contents of backup directory:"
ls -l "$BACKUP_DIR"

Automating Log Cleanup

Server logs can grow very large, consuming disk space. Automating their cleanup is vital.

We can use the find command to locate files older than a certain age and then delete them.

  • find /path: Start search in /path.
  • -type f: Look for regular files.
  • -name "*.log": Match files ending with .log.
  • -mmin +N: Modified more than N minutes ago.
  • -delete: Delete found files.

Log Cleanup Script Demo

This script creates a 'current' log file and an 'old' log file (simulated to be 2 minutes old). It then uses find to delete any log files in the dummy directory older than 1 minute.

#!/bin/bash

LOG_DIR="/tmp/coddykit_app_logs_demo"
OLD_MINUTES=1 # Files older than this will be deleted

mkdir -p "$LOG_DIR"

# Create a 'current' log file
touch "${LOG_DIR}/current_log_$(date +%H%M%S).log"

# Create an 'old' log file (simulated to be 2 minutes ago)
touch -d "2 minutes ago" "${LOG_DIR}/old_log_$(date +%H%M%S)_old.log"

echo "--- Before cleanup ---"
ls -l "$LOG_DIR"

echo "\nCleaning logs in $LOG_DIR older than $OLD_MINUTES minute(s)..."
# Find files in LOG_DIR that are regular files (*.log) and modified more than OLD_MINUTES ago
find "$LOG_DIR" -type f -name "*.log" -mmin +$OLD_MINUTES -delete

echo "\n--- After cleanup ---"
ls -l "$LOG_DIR"

Scripting Service Restarts

Services (like web servers or databases) can sometimes crash or need restarting after configuration changes.

We can automate checking their status and restarting them using systemctl (for systemd-based Linux distributions like Ubuntu, Debian, CentOS 7+).

  • systemctl is-active --quiet <service>: Check if service is active silently.
  • systemctl restart <service>: Restart the service.

Service Restart Script Demo

This script demonstrates the logic for restarting a service. Since running systemctl directly in this sandbox isn't possible, it simulates the process.

In a real server environment, you'd replace the echo lines with actual systemctl commands, often requiring sudo.

#!/bin/bash

SERVICE_NAME="my-dummy-web-app"

echo "Simulating service management for: $SERVICE_NAME"

# Check if the service is active (simulated)
# In a real script: if ! systemctl is-active --quiet $SERVICE_NAME; then
if [ "$SERVICE_NAME" = "my-dummy-web-app" ]; then # Always true for demo
  echo "Service $SERVICE_NAME is currently 'inactive' (simulated)."
  echo "Attempting to restart $SERVICE_NAME..."
  
  # Restart the service (simulated)
  # In a real script: sudo systemctl restart $SERVICE_NAME
  echo "Service $SERVICE_NAME restarted successfully (simulated)."
else
  echo "Service $SERVICE_NAME is already running (simulated)."
fi

echo "\nRemember: For real services like 'nginx' or 'apache2', you'd use: sudo systemctl restart nginx"

Basic System Health Checks

Automated health checks provide early warnings for potential server issues. Scripts can regularly monitor key metrics:

  • Disk Usage: Use df -h to check free space.
  • Memory Usage: Use free -h to see RAM usage.
  • System Load: uptime provides average load.

These checks can be integrated with alert systems to notify you if thresholds are exceeded.

Quick Check: Log Cleanup

You need to write a script to clean up log files in /var/log/myapp that are older than 30 days. Which find command would you use?

Recap & Next Steps

You've learned how to automate essential server tasks using Bash scripts:

  • Backups: Using tar for archiving with timestamps.
  • Log Cleanup: Employing find to delete old files.
  • Service Management: Interacting with services using systemctl.
  • Health Checks: Monitoring system resources like disk and memory.

These scripts form the foundation for maintaining robust and efficient servers. In the next lesson, we'll dive into error handling and logging within your scripts to make them even more reliable!

Frequently asked questions

Is the “Automating Server Tasks” lesson free?

Yes — the full text of “Automating Server Tasks” is free to read here on the web, and the Linux Server Deployment & SSH Mastery course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Linux Server Deployment & SSH Mastery course, upgrade to CoddyKit PRO.

What will I learn in “Automating Server Tasks”?

Write scripts to automate common administrative tasks such as backups, log cleanup, service restarts, and system health checks. You practise Linux Server Deployment & SSH Mastery with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Linux Server Deployment & SSH Mastery?

No prior experience is required. Linux Server Deployment & SSH Mastery on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Automating Server Tasks” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Linux Server Deployment & SSH Mastery lesson?

Yes. Every Linux Server Deployment & SSH Mastery lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Introduction to Bash Scripting
  2. Automating Server Tasks
  3. Error Handling and Logging in Scripts
  4. Functions, Arguments, and Reusable Scripts
← Back to Linux Server Deployment & SSH Mastery