Operations 7 min read

From Commands to Scripts: Essential Shell Automation for Linux Operations

This tutorial introduces shell scripting for Linux operations, covering core concepts, automation use cases, and two hands-on examples—daily log backup with retention and batch file extension renaming—plus beginner guidance on key syntax and learning approach.

Engineer Tang's Implementation Study Notes
Engineer Tang's Implementation Study Notes
Engineer Tang's Implementation Study Notes
From Commands to Scripts: Essential Shell Automation for Linux Operations

What Is a Shell Script?

A shell script is a text file containing a sequence of Linux/Unix commands arranged in logical order. By granting the file execute permission and running it, the commands execute automatically one after another. Think of it as a pre-written checklist: instead of manually typing "cd directory", "ls files", "rm useless files" each time, the script runs the checklist with a single command, automating repetitive tasks and boosting efficiency.

What Can Shell Scripts Do?

The core application of shell scripts is automation. Typical scenarios include:

Routine operations automation: scheduled server log backups, automatic cleanup of system junk files, periodic checks of server port status.

Batch processing tasks: bulk renaming of files, sending identical commands to multiple servers, bulk text data processing (e.g., extracting key information from logs).

Simplifying complex operations: encapsulating multi-step command sequences with conditional logic (e.g., proceed only if previous command succeeds) into a one-click script.

Assisting development and testing: automating code compilation, spinning up test environments, eliminating manual repetition.

In short, any task that requires repeatedly typing commands can likely be simplified with a shell script.

Hands-On Shell Script Examples

Example 1: Automatic Log Backup

Requirement: Back up the syslog file in /var/log daily, naming the backup "syslog_YYYY-MM-DD.tar.gz", and retain only the most recent 7 days of backups (automatically delete older ones).

Script content (create backup_log.sh with the following):

#!/bin/bash
# Define backup directory and log source directory
BACKUP_DIR="/backup/logs"
LOG_DIR="/var/log"
# Define backup filename (date format: YYYY-MM-DD)
DATE=$(date +%Y-%m-%d)
BACKUP_FILE="syslog_${DATE}.tar.gz"
# Check if backup directory exists, create if not
if [ ! -d "$BACKUP_DIR" ]; then
    mkdir -p "$BACKUP_DIR"
fi
# Start backup
tar -zcvf "$BACKUP_DIR/$BACKUP_FILE" "$LOG_DIR/syslog"
# Delete backups older than 7 days
find "$BACKUP_DIR" -name "syslog_*.tar.gz" -mtime +7 -delete
# Output completion message
echo "Backup completed! Backup file: $BACKUP_DIR/$BACKUP_FILE"

Usage:

Make the script executable: chmod +x backup_log.sh Test run manually: ./backup_log.sh Schedule via cron (daily at 2 AM): run crontab -e and add:

0 2 * * * /path/backup_log.sh

Example 2: Batch Rename File Extensions

Requirement: Change all files with a ".txt" extension in the current directory to ".doc".

Script content (create batch_rename.sh):

#!/bin/bash
# Iterate over all .txt files in current directory
for file in *.txt; do
    # Check if file exists (avoid error when no .txt files)
    if [ -f "$file" ]; then
        # Replace extension: .txt to .doc
        mv "$file" "${file%.txt}.doc"
        echo "Renamed: $file -> ${file%.txt}.doc"
    fi
done
echo "Batch rename completed!"

Both examples are practical for daily use; the core logic is simple and can be adapted to your needs (e.g., change directories, change file extensions).

Getting Started with Shell Scripting

Learn Basic Commands First : cd, ls, cp, mv, rm, cat, grep, find, etc.

Master Key Syntax : #!/bin/bash: Shebang line specifying the interpreter.

Variables: name="value", reference with $: echo $name.

Conditionals: if [ condition ]; then ... fi.

Loops: for var in list; do ... done.

Functions: function_name() { ... }.

Copy and Adapt : Find existing scripts online and modify them to fit your requirements.

Shell scripting isn't difficult—its essence is "commands + logic". Beginners can start with simple examples and practice repeatedly. If you have specific use cases or want to dive deeper into a topic, feel free to discuss in the comments.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Automationcronbashshell scriptinglinux operationsBeginner Tutorialbatch renamelog backup
Engineer Tang's Implementation Study Notes
Written by

Engineer Tang's Implementation Study Notes

Old Tang | Pseudo-full-stack tech player: writes code without going bald, manages projects without going crazy, delivers without staying up late. No formal tutorials here, only a "slacking-off" practical manual that cures system pain points. Focuses on Shell, SQL, Java, and delivery, turning complexity into simplicity and making efficiency fun.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.