Bash Script to Check CPU Usage Easily
Use the command
top -bn1 | grep 'Cpu(s)' | awk '{print 100 - $8 "% CPU used"}' inside a Bash script to check current CPU usage percentage.Examples
InputCPU idle is 90%
Output10% CPU used
InputCPU idle is 75.5%
Output24.5% CPU used
InputCPU idle is 0%
Output100% CPU used
How to Think About It
To check CPU usage, find the percentage of CPU idle time from system commands, then subtract it from 100% to get the used CPU percentage. This gives a simple number showing how busy the CPU is right now.
Algorithm
1
Run a system command to get CPU idle percentage.2
Extract the idle value from the command output.3
Calculate CPU usage as 100 minus idle percentage.4
Print the CPU usage percentage.Code
bash
#!/bin/bash cpu_idle=$(top -bn1 | grep 'Cpu(s)' | awk '{print $8}' | sed 's/,//') cpu_usage=$(echo "100 - $cpu_idle" | bc) echo "$cpu_usage% CPU used"
Output
10.5% CPU used
Dry Run
Let's trace a CPU idle value of 89.5% through the script
1
Get CPU idle
Command output: Cpu(s): 10.5% us, 0.0% sy, 0.0% ni, 89.5% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st Extracted idle: 89.5
2
Calculate usage
100 - 89.5 = 10.5
3
Print result
Output: 10.5% CPU used
| Step | Action | Value |
|---|---|---|
| 1 | Extract idle | 89.5 |
| 2 | Calculate usage | 10.5 |
| 3 | Print output | 10.5% CPU used |
Why This Works
Step 1: Extract CPU idle
The top command shows CPU stats; we use grep and awk to get the idle percentage from its output.
Step 2: Calculate CPU usage
CPU usage is the opposite of idle, so we subtract idle from 100 using bc for decimal math.
Step 3: Display result
The script prints the CPU usage with a percent sign to show how busy the CPU is.
Alternative Approaches
Using vmstat
bash
#!/bin/bash idle=$(vmstat 1 2|tail -1|awk '{print $15}') usage=$((100 - idle)) echo "$usage% CPU used"
This uses <code>vmstat</code> which samples CPU idle twice; it may be more accurate but slower.
Using mpstat
bash
#!/bin/bash idle=$(mpstat 1 1 | grep 'Average' | awk '{print $12}') usage=$(echo "100 - $idle" | bc) echo "$usage% CPU used"
Requires <code>mpstat</code> from sysstat package; gives detailed CPU stats.
Complexity: O(1) time, O(1) space
Time Complexity
The script runs a fixed number of commands once, so it takes constant time regardless of CPU load.
Space Complexity
Uses only a few variables to store numbers, so constant space.
Which Approach is Fastest?
Using top is fast and available on most systems; vmstat and mpstat may be slower or require extra packages.
| Approach | Time | Space | Best For |
|---|---|---|---|
| top command | O(1) | O(1) | Quick, no extra tools |
| vmstat command | O(1) | O(1) | More accurate sampling |
| mpstat command | O(1) | O(1) | Detailed CPU stats, needs sysstat |
Use
bc for decimal math in Bash when calculating CPU usage.Beginners often forget to subtract idle from 100, showing idle instead of usage.