Here are a few real-time shell script examples that you might encounter in practical scenarios:
File Backup Script:
#!/bin/bash# Source and destination directoriessource_dir="/path/to/source"backup_dir="/path/to/backup"# Create a timestamp for the backuptimestamp=$(date+%Y%m%d%H%M%S)# Archive the source directory and copy it to the backup directorytar-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.
Log Rotation Script:
#!/bin/bash# Log file pathlog_file="/path/to/logfile.log"# Maximum size in bytes for log filemax_size=1000000# Check if log file size exceeds the maximum sizeif [ $(stat-c%s"$log_file") -gt"$max_size" ]; then# Archive the log filemv"$log_file""$log_file.$(date+%Y%m%d%H%M%S)"# Create a new log filetouch"$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.
Database Backup Script:
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.