Practical Linux Shell Scripting Scenarios

This script gathers essential server metrics, including the hostname, network details, OS version, kernel data, CPU specifications, and memory capacity. It utilizes color codes to improve output readability.

#!/bin/bash
# Filename: server_status.sh

# Define color variables for terminal output
COLOR_RESET='\033[0m'
COLOR_HEADER='\033[1;36m'
COLOR_INFO='\033[1;33m'

# Print header
echo -e "${COLOR_HEADER}========== Server System Status ==========${COLOR_RESET}"

# Retrieve Hostname
echo -e "Hostname:       ${COLOR_INFO}$(hostname)${COLOR_RESET}"

# Retrieve IP Address (get primary IP via ip route)
CURRENT_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')
echo -e "IP Address:     ${COLOR_INFO}${CURRENT_IP}${COLOR_RESET}"

# Retrieve OS Version
echo -e "OS Version:     ${COLOR_INFO}$(cat /etc/os-release | grep PRETTY_NAME | cut -d '"' -f 2)${COLOR_RESET}"

# Retrieve Kernel Version
echo -e "Kernel Version: ${COLOR_INFO}$(uname -r)${COLOR_RESET}"

# Retrieve CPU Model
echo -e "CPU Model:      ${COLOR_INFO}$(lscpu | grep 'Model name' | awk -F: '{print $2}' | xargs)${COLOR_RESET}"

# Retrieve Total Memory
echo -e "Total Memory:   ${COLOR_INFO}$(free -h | awk '/^Mem:/ {print $2}')${COLOR_RESET}"

# Retrieve Disk Usage for main drives
echo -e "Disk Space:     ${COLOR_INFO}$(df -h | grep '^/dev/sd' | awk '{print $1 ": " $5}')${COLOR_RESET}"

echo -e "${COLOR_HEADER}===========================================${COLOR_RESET}"

Execution Tip: Use bash -n script_name.sh to check for syntax errors and bash -x script_name.sh to debug the execution logic.

2. Automated Directory Backup

The following script creates a daily backup of the system configuration directory. It organizes backups by date stamp in a designated repository.

#!/bin/bash
# Filename: daily_backup.sh

LOG_COLOR='\033[1;35m'
RESET='\033[0m'
BACKUP_ROOT="/data/backups"
SOURCE_DIR="/etc"
TODAY=$(date +%Y-%m-%d)

echo -e "${LOG_COLOR}Initiating backup sequence...${RESET}"
sleep 1

# Create backup directory if missing
[ ! -d "$BACKUP_ROOT" ] && mkdir -p "$BACKUP_ROOT"

# Perform the copy operation
cp -r "$SOURCE_DIR" "${BACKUP_ROOT}/config_${TODAY}"

echo -e "${LOG_COLOR}Backup completed successfully.${RESET}"

3. Identifying Maximum Disk Utilization

This utility scans all mounted file systems to determine the partition with the highest storage usage percentage and returns the value.

#!/bin/bash
# Filename: max_disk_usage.sh

# Filter df output for percentage, remove symbols, sort numerically, and take the top value
MAX_USAGE=$(df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{print $5}' | tr -d '%' | sort -rn | head -n 1)

echo "The highest disk utilization rate is currently: ${MAX_USAGE}%"

4. Monitoring Remote Connections

This script analyzes established remote connections by counting the number of sessions per unique IP address and sorting them by frequency.

#!/bin/bash
# Filename: connection_audit.sh

# Extract login info, isolate IPs, count occurrences, and sort
echo "Active Remote Connections:"
w -h | awk '{print $3}' | sort | uniq -c | sort -rn

5. Argument Handlnig and File Analysis

This script validates command-line arguments. If a valid file is provided, it counts the number of empty lines contained within.

#!/bin/bash
# Filename: analyze_file.sh

# Check argument count
if [ $# -eq 0 ]; then
    echo "Error: Please provide a file path as an argument."
    exit 1
fi

TARGET_FILE="$1"

# Check if the path exists and is a regular file
if [ -f "$TARGET_FILE" ]; then
    # Count empty lines using grep
    BLANK_COUNT=$(grep -c "^$" "$TARGET_FILE")
    echo "File '$TARGET_FILE' contains $BLANK_COUNT empty lines."
else
    echo "Error: The specified path is not a valid file."
fi

6. Network Connectivity Check

This tool accepts an IP address as input and verifies network reachability using ICMP ping requests.

#!/bin/bash
# Filename: net_check.sh

if [ $# -ne 1 ]; then
    echo "Usage: $0 [IP_ADDRESS]"
    exit 1
fi

TARGET_IP="$1"

# Send 1 packet, wait 1 second, suppress output
ping -c 1 -W 1 "$TARGET_IP" > /dev/null 2>&1

if [ $? -eq 0 ]; then
    echo "Success: Host at $TARGET_IP is reachable."
else
    echo "Failure: Host at $TARGET_IP is unreachable."
fi

7. Storage and Inode Capacity Alert

A monitoring script that checks both disk space usage and inode utilization. If either metric exceeds the 80% threshold, it broadcasts a warning to all logged-in users.

#!/bin/bash
# Filename: capacity_monitor.sh

THRESHOLD=80

# Check Disk Usage
DISK_VAL=$(df | grep -vE '^Filesystem|tmpfs' | awk '{print $5}' | tr -d '%' | sort -rn | head -n 1)
if [ "$DISK_VAL" -ge "$THRESHOLD" ]; then
    wall "Warning: Disk space usage has exceeded ${THRESHOLD}%!"
fi

# Check Inode Usage
INODE_VAL=$(df -i | grep -vE '^Filesystem|tmpfs' | awk '{print $5}' | tr -d '%' | sort -rn | head -n 1)
if [ "$INODE_VAL" -ge "$THRESHOLD" ]; then
    wall "Warning: Inode usage has exceeded ${THRESHOLD}%!"
fi

8. Verifying File Read/Write Permissions

This script determines if the current user lacks both read and write permissions for a specified file.

#!/bin/bash
# Filename: check_perms.sh

FILE_PATH="$1"

if [ -z "$FILE_PATH" ]; then
    echo "Please provide a file path."
    exit 1
fi

if [ -f "$FILE_PATH" ]; then
    # Check if file is NOT readable AND NOT writable
    if [ ! -r "$FILE_PATH" ] && [ ! -w "$FILE_PATH" ]; then
        echo "Access Denied: You have neither read nor write permissions for '$FILE_PATH'."
    else
        echo "Access Granted: You have read or write permissions for '$FILE_PATH'."
    fi
else
    echo "Error: '$FILE_PATH' is not a valid file."
fi

9. Automating Script Permissions

This snippet prompts the user for a filename. If the file is a shell script (ending in .sh), it automatically grants execute permissions.

#!/bin/bash
# Filename: auto_exec.sh

read -p "Enter the script filename: " USER_FILE

if [ -f "$USER_FILE" ]; then
    if [[ "$USER_FILE" == *.sh ]]; then
        chmod +x "$USER_FILE"
        echo "Execute permissions added to $USER_FILE"
    else
        echo "Notice: The file is not a .sh script."
    fi
else
    echo "Error: File not found."
fi

10. Managing System Logins

These scripts demonstrate how to toggle the ability for regular users to log into the system by creating or removing the /etc/nologin file.

Disable User Logins:

#!/bin/bash
if [ -f /etc/nologin ]; then
    echo "Standard user logins are already disabled."
else
    touch /etc/nologin
    echo "Standard user logins have been disabled."
fi

Enable User Logins:

#!/bin/bash
if [ -f /etc/nologin ]; then
    rm -f /etc/nologin
    echo "Standard user logins have been enabled."
else
    echo "Standard user logins are already enabled."
fi

Tags: bash shell-scripting linux-administration system-automation devops

Posted on Fri, 10 Jul 2026 17:07:34 +0000 by w4seem