Bash shell scripting for monitoring system resources.

Bash shell scripting is a powerful tool for monitoring system resources in Linux and Unix-based systems. You can use various built-in commands and tools to gather information about CPU usage, memory usage, disk space, and more. Here’s a basic example of a Bash script to monitor system resources:


# Get the current date and time
timestamp=$(date +"%Y-%m-%d %H:%M:%S")

# Get CPU usage percentage
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | awk -F. '{print $1}')

# Get memory usage percentage
mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

# Get disk usage percentage of the root filesystem
disk_usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')

# Print the results
echo "Timestamp: $timestamp"
echo "CPU Usage: $cpu_usage%"
echo "Memory Usage: $mem_usage%"
echo "Disk Usage: $disk_usage%"

# You can add more monitoring commands as needed (e.g., network, processes, etc.)

# Save the results to a log file
echo "$timestamp,$cpu_usage,$mem_usage,$disk_usage" >> system_monitor.log

In this script:

  1. We use the date command to get the current date and time.
  2. We use the top command to get CPU usage percentage.
  3. We use the free command to get memory usage percentage.
  4. We use the df command to get disk usage percentage for the root filesystem.
  5. We print the results to the console.
  6. We also append the results to a log file named system_monitor.log for historical data.

You can customize this script to monitor additional resources or use different commands based on your specific monitoring requirements. You can also schedule this script to run at regular intervals using tools like cron to create a system resource monitoring solution.

Leave a Comment

Your email address will not be published. Required fields are marked *