# 10 Corporate Real-Time Shell Scripts

### Backup Script Script

```bash
SOURCE="/home/ubuntu/Test01"
DESTINATION="/home/ubuntu/Test02/"
DATE=$(date +%Y-%m-%d_%H-%M-%S)

# Create backup directory and copy files

mkdir -p $DESTINATION/$DATE
cp -r $SOURCE $DESTINATION/$DATE
echo "Backup completed on $DATE"
```

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:

```bash
text* * * * * /path/to/backup_script.sh
```

This configuration will execute the backup script every minute[5](https://www.windmill.dev/blog/edit-crontabs). 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
bash#!/bin/bash

THRESHOLD=80

df -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}%"
    fi
done
```

## **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
bash#!/bin/bash

SERVICE="nginx"

if systemctl is-active --quiet $SERVICE; then
    echo "$SERVICE is running"
else
    echo "$SERVICE is not running"
    systemctl start $SERVICE
fi
```

**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
bash#!/bin/bash

HOST="google.com"
OUTPUT_FILE="/home/ubuntu/output.txt"

if ping -c 1 $HOST &> /dev/null
then
    echo "$HOST is reachable" >> $OUTPUT_FILE
else
    echo "$HOST is not reachable" >> $OUTPUT_FILE
fi
```

**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
bash#!/bin/bash

DB_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.sql

echo "Database backup completed: $BACKUP_DIR/$DB_NAME-$DATE.sql"
```

**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
bash#!/bin/bash

uptime -p
```

**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
bash#!/bin/bash

netstat -tuln | grep LISTEN
```

**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
bash#!/bin/bash

apt-get update && apt-get upgrade -y && apt-get autoremove -y && apt-get clean
echo "System packages updated and cleaned up"
```

**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
bash#!/bin/bash

URLS=("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
```

**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
bash#!/bin/bash

ps aux --sort=-%mem | head -n 10
```

**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.
