The provided command is a shell script snippet that retrieves and displays the current CPU and RAM usage percentages. Let's break it down step by step to understand how it works:
Command Breakdown
1. CPU Usage Calculation
top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}'
top -bn1: Runs the top command in batch mode (-b) for one iteration (-n1). This outputs system statistics in a single snapshot.
grep "Cpu(s)": Filters the line containing CPU usage information. The line typically looks like this:
%Cpu(s): 10.5 us, 5.3 sy, 0.0 ni, 84.2 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
Here, us (user) and sy (system) represent the CPU usage percentages.
awk '{print $2 + $4}': Extracts the second ($2, user CPU usage) and fourth ($4, system CPU usage) fields and adds them together. This gives the total CPU usage percentage.
2. RAM Usage Calculation
free -m | awk '/Mem/{printf("%.2f%"), $3/$2*100}'
3. Final Output
echo "CPU: $(...)% RAM: $(...)"
Potential Issues and Improvements
-
Locale-Specific Decimal Separator:
-
Error Handling:
-
Improved Readability:
Final Version
Here’s the improved and more robust version of the command:
#!/bin/bash
# Check if required commands are available
if ! command -v top &> /dev/null || ! command -v free &> /dev/null; then
echo "Error: Required commands (top, free) are not available."
exit 1
fi
# Calculate CPU usage
cpu_usage=$(LC_NUMERIC=C top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
# Calculate RAM usage
ram_usage=$(free -m | awk '/Mem/{printf("%.2f"), $3/$2*100}')
# Display the results
echo "CPU: ${cpu_usage}% RAM: ${ram_usage}%"
Output Example
If the CPU usage is 15.8% and RAM usage is 25.3%, the output will be:
CPU: 15.8% RAM: 25.3%
This script is now more reliable, readable, and portable across different environments.