DEV Community

Asad
Asad

Posted on • Originally published at blog.automation-dev.us on

10 Corporate Real-Time Shell Scripts

Backup Script Script

SOURCE="/home/ubuntu/Test01"DESTINATION="/home/ubuntu/Test02/"DATE=$(date +%Y-%m-%d_%H-%M-%S)# Create backup directory and copy filesmkdir -p $DESTINATION/$DATEcp -r $SOURCE $DESTINATION/$DATEecho "Backup completed on $DATE"
Enter fullscreen mode Exit fullscreen mode

Explanation

SOURCE : The directory to be backed up. DESTINATION: The directory where the backup will be stored. DATE : Captures the current date and time to create a unique backup folder.

mkdir -p $DESTINATION/$DATE: Creates the backup directory if it does not exist.

cp -r $SOURCE $DESTINATION/$DATE: Copies the contents of the source directory to the backup directory.

echo "Backup completed on $DATE": Outputs a message indicating the completion of the backup.

Scheduling the backup with Cron

To schedule regular execution of the backup script, utilize the crontab editor by running the following command:

crontab -e

Once in the editor, add the following line to configure the backup schedule:

text* * * * * /path/to/backup_script.sh
Enter fullscreen mode Exit fullscreen mode

This configuration will execute the backup script every minute5. Modify the cron schedule parameters to align with your desired backup frequency.

Disk Usage Monitoring Script

Script Overview

This Bash script monitors disk usage across partitions and issues warnings when usage exceeds a predefined threshold.

bash#!/bin/bashTHRESHOLD=80df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;do usage=$(echo $output | awk '{ print $1}' | cut -d'%' -f1) partition=$(echo $output | awk '{ print $2 }') if [$usage -ge $THRESHOLD]; then echo "Warning: Disk usage on $partition is at ${usage}%" fidone
Enter fullscreen mode Exit fullscreen mode

Functionality Breakdown

  1. Threshold Setting : The script initializes with a disk usage threshold of 80%.

  2. Disk Usage Data Collection : Utilizes df -H to retrieve disk usage information in a human-readable format.

  3. Data Filtering : Employs grep to exclude non-essential filesystem entries.

  4. Data Extraction : Uses awk to isolate usage percentages and partition names.

  5. Iterative Processing : Processes each filtered entry using a while loop.

  6. Usage Calculation : Extracts the numerical usage percentage from each entry.

  7. Partition Identification : Isolates the partition name for each entry.

  8. Threshold Comparison : Compares the usage against the predefined threshold.

  9. Alert Generation : Outputs a warning message for partitions exceeding the threshold.

Service Health Check

This script checks if a specified service is running and starts it if not.

bash#!/bin/bashSERVICE="nginx"if systemctl is-active --quiet $SERVICE; then echo "$SERVICE is running"else echo "$SERVICE is not running" systemctl start $SERVICEfi
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • SERVICE: Specifies the name of the service to check (nginx in this example).

  • systemctl is-active --quiet $SERVICE: Checks if the service is running.

  • If the service is running, it prints a confirmation message.

  • If it is not running, it prints a message and attempts to start the service.

Network Connectivity Check

This script checks network connectivity to a specified host.

bash#!/bin/bashHOST="google.com"OUTPUT_FILE="/home/ubuntu/output.txt"if ping -c 1 $HOST &> /dev/nullthen echo "$HOST is reachable" >> $OUTPUT_FILEelse echo "$HOST is not reachable" >> $OUTPUT_FILEfi
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • HOST: Specifies the hostname to check.

  • OUTPUT_FILE: Defines where to write the output.

  • ping -c 1 $HOST &> /dev/null: Pings the host once, suppressing output.

  • Depending on the ping result, it writes a reachability status to the output file.

Database Backup

This script creates a backup of a specified MySQL database.

bash#!/bin/bashDB_NAME="mydatabase"BACKUP_DIR="/path/to/backup"DATE=$(date +%Y-%m-%d_%H-%M-%S)mysqldump -u root -p $DB_NAME > $BACKUP_DIR/$DB_NAME-$DATE.sqlecho "Database backup completed: $BACKUP_DIR/$DB_NAME-$DATE.sql"
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • DB_NAME: Specifies the database to back up.

  • BACKUP_DIR: Defines where to store the backup.

  • DATE: Captures the current date and time for a unique filename.

  • mysqldump command creates a SQL dump of the database.

  • The echo statement confirms the backup completion and location.

System Uptime Check

This simple script displays the system's uptime.

bash#!/bin/bashuptime -p
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • uptime -p: Prints the system uptime in a human-readable format.

Listening Ports Monitor

This script lists all listening ports and their associated services.

bash#!/bin/bashnetstat -tuln | grep LISTEN
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • netstat -tuln: Lists all TCP and UDP listening ports.

  • grep LISTEN: Filters the output to show only listening ports.

Automatic Package Updates

This script updates and cleans up system packages.

bash#!/bin/bashapt-get update && apt-get upgrade -y && apt-get autoremove -y && apt-get cleanecho "System packages updated and cleaned up"
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • apt-get update: Updates the package list.

  • apt-get upgrade -y: Upgrades all installed packages.

  • apt-get autoremove -y: Removes unnecessary packages.

  • apt-get clean: Cleans up the package cache.

  • The echo statement confirms the completion of updates and cleanup.

HTTP Response Time Monitor

This script checks HTTP response times for specified URLs.

bash#!/bin/bashURLS=("https://www.devopsshack.com/" "https://www.linkedin.com/")for URL in "${URLS[@]}"; do RESPONSE_TIME=$(curl -o /dev/null -s -w '%{time_total}\n' $URL) echo "Response time for $URL: $RESPONSE_TIME seconds"done
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • URLS: An array of URLs to check.

  • The for loop iterates over each URL.

  • curl command fetches each URL and measures the total response time.

  • The script prints the response time for each URL.

System Process and Memory Usage Monitor

This script displays the top processes by memory usage.

bash#!/bin/bashps aux --sort=-%mem | head -n 10
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • ps aux: Lists all running processes.

  • --sort=-%mem: Sorts processes by memory usage in descending order.

  • head -n 10: Displays only the top 10 processes.

These scripts provide valuable tools for various DevOps tasks, from system monitoring to backup and maintenance operations.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay