Intermediate · 25 min · practise every command in the built-in terminal

🛠 Project: Server Health Check

A full disk takes a server down without warning: logs can't be written, databases stop. An admin doesn't wait for that. A small script looks every 15 minutes and raises the alarm in time.

What the script has to do

~/scripts/health.sh LIMIT (without a limit: 80):

  1. Print how full the disk is: Disk: 8%
  2. Print how much memory is in use: Memory: 305 MB used
  3. Show the 3 processes that use the most CPU
  4. If the disk is fuller than LIMIT %: print WARNING: … and exit with status 1, so other tools can see something is wrong
  5. Add a line with the date and time to ~/logs/health.log on every run
  6. Run every 15 minutes, from cron

Building blocks

df / | awk 'NR == 2 {print $5}'           # 8%: the "Use%" column of the line for /
df / | awk 'NR == 2 {print $5}' | tr -d %  # 8: just the number
free -m | awk '/Mem/ {print $3}'          # Memory used, in MB
ps aux --sort=-%cpu | head -4             # The header and the 3 busiest processes
LIMIT=${1:-80}                            # The first argument, or 80
if [ "$DISK" -gt "$LIMIT" ]; then …; fi   # -gt: greater than (numbers)
date '+%F %T'                             # 2026-10-25 14:30:00
echo "…" >> ~/logs/health.log             # >> adds a line, > would replace the file

💡 Test the warning without filling the disk: give a small limit, ~/scripts/health.sh 5, and check echo $? right after.

Practice tasks

  1. Create ~/scripts/health.sh, a bash script, and make it executable
  2. It prints the disk usage (Disk: N%) and the memory used (Memory: N MB used)
  3. It shows the 3 processes that use the most CPU
  4. With a limit of 5% it warns, and exits with status 1
  5. Every run adds a line with the date and time to ~/logs/health.log
  6. Make it run every 15 minutes

Commands in this lesson

Projects