Advertisement
linuxserver Keeping your Linux system healthy is easier with Bash scripts. In this tutorial, you’ll get ready-to-use scripts to monitor CPU, memory, and disk usage, check running processes, and clean unnecessary files. These scripts save time and prevent common system issues.

Bash Scripts for System Monitoring and Maintenance

5 Min Read Verified Content

Script 1: Monitor CPU Usage

#!/bin/bash # Display CPU usage every 5 seconds echo "Monitoring CPU usage..." while true; do echo "-------------------------" echo "$(date)" top -bn1 | grep "Cpu(s)" sleep 5 done

Benefit:

  • Real-time CPU usage monitoring

  • Can be stopped anytime with Ctrl+C



Script 2: Monitor Memory Usage

#!/bin/bash # Check free and used memory echo "Memory status:" free -h echo "Top 5 memory-consuming processes:" ps aux --sort=-%mem | head -n 6

Benefit:

  • Quickly identify memory usage and top memory-consuming processes

  • Useful for diagnosing slow systems



Script 3: List Large Files

#!/bin/bash # Find files larger than 100MB in home directory echo "Searching for files larger than 100MB..." find $HOME -type f -size +100M -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'

Benefit:

  • Identify large files taking unnecessary space

  • Helps clean up disk space efficiently



Script 4: Monitor Running Processes

#!/bin/bash # List top CPU-consuming processes echo "Top CPU-consuming processes:" ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -n 11

Benefit:

  • Quickly see which processes are consuming the most CPU

  • Useful for server performance monitoring



Script 5: Automatic Cleanup

#!/bin/bash # Remove old log files and cache echo "Cleaning up old logs and cache..." find /var/log -type f -name "*.log" -mtime +30 -exec rm -f {} \; rm -rf ~/.cache/* echo "Cleanup completed!"

Benefit:

  • Keeps logs and cache from filling up disk

  • Can be automated with cron weekly or monthly



Summary

These scripts help you:

  1. Monitor CPU and memory usage

  2. Identify large files and clean disk space

  3. Check running processes for resource usage

  4. Automate cleanup tasks

Advertisement
Back to Linuxserver