Explanation:
Shebang:
#!/bin/bash
specifies that this script should be interpreted using the Bash shell.get_cpu_usage Function: Uses
top
command to get CPU usage information:-bn1
: Runstop
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.
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.
- Adjust the
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.
0 Comments