5 Useful Bash Scripts for Everyday Tasks

5 Useful Bash Scripts for Everyday Tasks

Objectives:

  • Learn to write and understand practical Bash scripts for common automation tasks.

  • Develop scripts that interact with files, directories, logs, and system information.

  • Apply error handling, input validation, and logging to these scripts.


Chapter Outline:

1. Disk Usage Report

Script Overview:

This script generates a detailed disk usage report for the user, highlighting space usage by directories.

#!/bin/bash

# Check if directory path is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <directory_path>"
    exit 1
fi

directory="$1"

# Check if the directory exists
if [ ! -d "$directory" ]; then
    echo "Directory not found: $directory"
    exit 1
fi

# Display disk usage report
du -sh "$directory"/* | sort -rh > disk_usage_report.txt
echo "Disk usage report saved to disk_usage_report.txt"

https://github.com/bc0de0/bash-scripts/blob/master/disc_usage.sh

Explanation:

  1. Argument Validation:

    • Checks if the user provides a directory argument.

    • Verifies if the directory exists.

  2. Disk Usage Report:

    • The du -sh command displays the disk usage of all items in the directory, and the result is sorted by size (sort -rh).

  3. Output to File:

    • The report is saved as disk_usage_report.txt.

Real-World Use:

This script can be used to monitor disk space usage and identify large files that need cleaning.


2. Monitoring Active Network Connections

Script Overview:

A script that monitors active network connections and logs them to a file for later analysis.

#!/bin/bash

log_file="network_connections.log"

# Capture active network connections using netstat
echo "Active network connections:" >> "$log_file"
netstat -tunapl >> "$log_file"
echo "Captured at: $(date)" >> "$log_file"
echo "----------------------------" >> "$log_file"

echo "Network connections logged to $log_file"

https://github.com/bc0de0/bash-scripts/blob/master/net_chk.sh

Explanation:

  1. netstat Command:

    • netstat -tunapl shows active network connections along with their listening ports (t for TCP, u for UDP, n for numeric IPs, a for all connections, p for programs).

  2. Logging:

    • The output of netstat is appended to network_connections.log, which includes a timestamp ($(date)).

Real-World Use:

This is useful for monitoring network activity, detecting potential intrusions, or identifying suspicious connections.


3. Automated Backup of Log Files

Script Overview:

A script to automate the backup of system log files.

#!/bin/bash

# Define source and backup directories
log_dir="/var/log"
backup_dir="/backup/logs"
timestamp=$(date +"%Y%m%d_%H%M%S")

# Check if backup directory exists, if not create it
if [ ! -d "$backup_dir" ]; then
    mkdir -p "$backup_dir"
fi

# Archive and compress log files
tar -czf "$backup_dir/log_backup_$timestamp.tar.gz" -C "$log_dir" .

echo "Log backup completed: log_backup_$timestamp.tar.gz"

https://github.com/bc0de0/bash-scripts/blob/master/log_backup.sh

Explanation:

  1. Directory Setup:

    • Checks if the backup directory exists; if not, it creates it.

  2. Backup and Compression:

    • Uses tar to archive and compress the log files into a .tar.gz file, saved with a timestamp for easy identification.

Real-World Use:

This script automates the backup of log files, ensuring important logs are archived regularly for auditing or forensic analysis.


4. Find and Kill Resource-Heavy Processes

Script Overview:

A script to find processes consuming too much CPU or memory and prompt the user to kill them.

#!/bin/bash

# Display top 5 CPU-consuming processes
echo "Top 5 CPU-consuming processes:"
ps -eo pid,comm,%cpu --sort=-%cpu | head -n 6

# Ask user if they want to kill any process
read -p "Enter the PID of the process to kill (or press Enter to skip): " pid

# If the user provided a PID, kill the process
if [ -n "$pid" ]; then
    kill -9 "$pid"
    echo "Process $pid killed."
else
    echo "No process killed."
fi

https://github.com/bc0de0/bash-scripts/blob/master/proc_kill.sh

Explanation:

  1. Display Top CPU-Consuming Processes:

    • ps -eo pid,comm,%cpu lists processes along with their PID, command name, and CPU usage, sorted by CPU usage.

  2. User Input:

    • Prompts the user to decide whether to kill a resource-heavy process.

  3. Kill Process:

    • If a PID is provided, the script kills that process using kill -9.

Real-World Use:

This script helps system administrators manage server resources by identifying and terminating processes that consume excessive CPU or memory.


5. Automated System Health Check

Script Overview:

A script that checks system health by gathering key system information and logs it.

#!/bin/bash

log_file="system_health_check.log"

# System uptime
echo "System Uptime:" >> "$log_file"
uptime >> "$log_file"
echo "----------------------------" >> "$log_file"

# Memory usage
echo "Memory Usage:" >> "$log_file"
free -h >> "$log_file"
echo "----------------------------" >> "$log_file"

# Disk usage
echo "Disk Usage:" >> "$log_file"
df -h >> "$log_file"
echo "----------------------------" >> "$log_file"

# Top 5 processes by CPU usage
echo "Top 5 CPU-consuming processes:" >> "$log_file"
ps -eo pid,comm,%cpu --sort=-%cpu | head -n 6 >> "$log_file"
echo "----------------------------" >> "$log_file"

echo "System health check logged to $log_file"

https://github.com/bc0de0/bash-scripts/blob/master/sys_health.sh

Explanation:

  1. System Information:

    • The script gathers uptime, memory usage (free -h), and disk usage (df -h).

  2. CPU Processes:

    • Captures the top 5 CPU-consuming processes.

  3. Logging:

    • All the gathered information is logged in a file for future reference.

Real-World Use:

This script is useful for performing quick system health checks, making it easier to monitor resource utilization on servers or workstations.


Last updated