Advertisement

Shell Script For CPU Usage Tracker Script

Linux Shell Script For CPU Usage Tracker Script 

CPU Usage Tracker Script

#!/bin/bash
output_file="cpu_usage_log.txt"
# Log current CPU usage to a file with timestamp
echo "$(date) $(top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d.
-f1)%" >> "$output_file"
echo "CPU usage logged."

Shell script to track CPU usage can be helpful for monitoring system performance over time or for diagnosing issues related to resource consumption

#!/bin/bash

# Function to get CPU usage percentage
get_cpu_usage() {
    CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
    echo "Current CPU Usage: $CPU_USAGE%"
}

# Main loop to track CPU usage
while true; do
    get_cpu_usage
    sleep 5  # Adjust sleep duration (in seconds) as needed
    clear   # Comment this out if you don't want to clear the screen after each update
done

Explanation:

  1. Shebang: #!/bin/bash specifies that this script should be interpreted using the Bash shell.

  2. get_cpu_usage Function: Uses top command to get CPU usage information:

    • -bn1: Runs top in batch mode for one iteration.
    • grep "Cpu(s)": Filters lines containing CPU usage information.
    • sed "s/.*, *\([0-9.]*\)%* id.*/\1/": Extracts the CPU idle percentage.
    • awk '{print 100 - $1}': Calculates and prints the CPU usage percentage by subtracting idle percentage from 100.
  3. Main Loop: Continuously calls get_cpu_usage function in a loop.

    • Adjust the sleep duration (in seconds) as needed to control how frequently CPU usage is checked.
    • clear: Clears the screen after each update to show fresh CPU usage information. Comment out this line if you prefer not to clear the screen.

Usage:

  • Save this script to a file, e.g., track_cpu_usage.sh.
  • Make it executable with chmod +x track_cpu_usage.sh.
  • Run the script with ./track_cpu_usage.sh.

Notes:

  • Customization: You can modify the script to output CPU usage to a log file instead of printing to the screen. This might involve redirecting the output of get_cpu_usage to a file (echo "$(get_cpu_usage)" >> cpu_usage.log).

  • Enhancements: Depending on your needs, you might add functionality to monitor specific processes or thresholds and trigger alerts or actions based on CPU usage.

  • Resource Impact: Continuous monitoring scripts like this can consume resources (CPU, memory). Ensure it doesn't interfere with other critical processes or impact system performance significantly.

This script provides a basic framework for tracking CPU usage in a Unix-like environment using standard command-line tools (top, grep, sed, awk). Depending on your requirements, you can expand upon it to include more detailed monitoring or integrate with monitoring systems for broader system management.

Post a Comment

0 Comments