Example Useful Scripts

Here are a few real-time shell script examples that you might encounter in practical scenarios:

  1. File Backup Script:

#!/bin/bash

# Source and destination directories
source_dir="/path/to/source"
backup_dir="/path/to/backup"

# Create a timestamp for the backup
timestamp=$(date +%Y%m%d%H%M%S)

# Archive the source directory and copy it to the backup directory
tar -czf "$backup_dir/backup_$timestamp.tar.gz" "$source_dir"

This script creates a backup of a specified source directory by creating a compressed tarball archive and storing it in the backup directory. It uses the tar command to create the archive.

  1. Log Rotation Script:

#!/bin/bash

# Log file path
log_file="/path/to/logfile.log"

# Maximum size in bytes for log file
max_size=1000000

# Check if log file size exceeds the maximum size
if [ $(stat -c %s "$log_file") -gt "$max_size" ]; then
    # Archive the log file
    mv "$log_file" "$log_file.$(date +%Y%m%d%H%M%S)"

    # Create a new log file
    touch "$log_file"
fi

This script performs log rotation by checking the size of a log file. If the size exceeds a specified limit, it archives the existing log file by appending the current timestamp and creates a new empty log file. It uses the stat command to get the file size and performs a comparison using an if statement.

  1. Database Backup Script:

#!/bin/bash

# Database credentials
db_user="username"
db_password="password"
db_name="database_name"

# Backup directory
backup_dir="/path/to/backup"

# Create a timestamp for the backup
timestamp=$(date +%Y%m%d%H%M%S)

# Dump the database to a SQL file
mysqldump -u "$db_user" -p"$db_password" "$db_name" > "$backup_dir/backup_$timestamp.sql"

This script performs a backup of a MySQL database by using the mysqldump command. It dumps the database to a SQL file and stores it in the backup directory. It requires the MySQL database credentials and the desired backup directory to be specified.

These examples provide a glimpse into the real-world usage of shell scripts. Shell scripts can be utilized in a wide range of scenarios, including automation, system administration, data processing, and more. The complexity and functionality of the scripts can vary based on specific requirements and needs.

Last updated