Shell Script Examples for Beginners

Learn practical examples of creating and running shell scripts in this friendly guide.
By Taylor

Introduction to Shell Scripting

Shell scripting is a powerful way to automate tasks on Unix/Linux systems. By writing scripts, you can execute a series of commands with just one command, saving you time and effort. In this guide, we’ll explore three diverse examples of creating and running a shell script that you can easily follow, regardless of your experience level.

Example 1: Backup Your Documents

Context

Backing up important files is crucial to prevent data loss. This shell script will copy your Documents folder to an external drive.

#!/bin/bash
# This script creates a backup of the Documents folder

# Define source and destination directories
SOURCE=~/Documents
DESTINATION=/mnt/external_drive/Backup_Documents

# Create the destination directory if it doesn't exist
mkdir -p "$DESTINATION"

# Copy files from source to destination
cp -r "$SOURCE"/* "$DESTINATION"

# Print a message indicating completion
echo "Backup completed successfully!"

Notes

  • Make sure to replace /mnt/external_drive with the actual path to your external drive.
  • You can run this script daily using a cron job to ensure your files are always backed up.

Example 2: Monitor Disk Space

Context

Keeping an eye on disk space is essential for system maintenance. This script checks the available disk space and alerts you if it falls below a certain threshold.

#!/bin/bash
# This script monitors disk space and alerts if below threshold

# Set threshold to 10% free space
THRESHOLD=10

# Get the current available space in percentage
AVAILABLE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')

# Check if available space is below threshold
if [ "$AVAILABLE" -gt "$THRESHOLD" ]; then
    echo "Disk space is OK: $AVAILABLE% free"
else
    echo "Warning: Disk space is low at $AVAILABLE% free!"
fi

Notes

  • You can customize the threshold by changing the value of THRESHOLD.
  • Consider adding this script to your crontab to run it periodically and get alerts.

Example 3: Simple Hello World Script

Context

If you’re just starting with shell scripting, writing a simple