In this lesson, you will learn how to transform raw, cluttered system process data into clear, human-readable reports using conditional logic within your scripts.
When you run commands like ps aux, you get a wall of text that is difficult to parse at a glance. To build a useful report, we need to extract specific columns and apply "conditional formatting"—meaning we change the output based on the values we find.
Logic-Driven Reporting
The core idea is to pipe your process data into a while read loop, then use if statements or arithmetic evaluation to categorize the data. For example, you might want to highlight processes that are consuming too much CPU or memory.
Here is how you can generate a simple "Alert Report" for high-usage processes:
#!/bin/bash
# Extracting PID, %CPU, and Command
ps -eo pid,pcpu,comm --no-headers | while read -r pid cpu cmd; do
# Use parameter expansion to strip decimals for comparison
int_cpu=${cpu%.*}
if [ "$int_cpu" -gt 50 ]; then
printf "[ALERT] PID: %s | CPU: %s%% | Task: %s\n" "$pid" "$cpu" "$cmd"
else
printf "[OK] PID: %s | CPU: %s%% | Task: %s\n" "$pid" "$cpu" "$cmd"
fi
done
Why this matters
By injecting logic into your reporting pipeline, you stop being a passive observer of system output and start acting as a data filter.
- Filtering: You decide what information is "noise" and what is "signal."
- Formatting: Using
printfallows you to align columns and label data, making your reports professional and readable. - Conditionals: By checking values (like CPU usage > 50%), you can trigger visual cues like
[ALERT]tags, allowing you to identify performance bottlenecks instantly.
Instead of outputting raw text, you are now creating a structured interface that communicates the status of your system effectively. This technique is essential for building monitoring scripts that provide actionable feedback rather than overwhelming logs.
Key Takeaway: Conditional formatting allows you to transform raw, machine-readable system streams into prioritized, human-readable alerts by applying logic at the point of display.