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.
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!"
/mnt/external_drive
with the actual path to your external drive.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
THRESHOLD
.If you’re just starting with shell scripting, writing a simple