Bash commands

chevron-rightOne linerhashtag

wc (word count) is used to count lines, words, and characters in text.

eg. count total pod
wc -l → counts the number of lines.
kubectl get pods | wc -l

count total running process
ps aux | wc -l

wc -w → counts the number of words.

wc -c → counts the number of bytes/characters.

find matching string in output
kubectl get pods -A | grep "loki"

Get usernames from /etc/passwd (colon : separated file)
cat /etc/passwd | cut -d':' -f1

tee file.txt → save + show output
Example: Save logs to a file while still printing them
kubectl logs mypod | tee pod.log


-a for append not overwrite
ls -l | tee -a files.txt

sort uniques
cat cities.txt | sort | uniq

Example: Replace "error" with "warning" in a log file
cat app.log | sed 's/error/warning/'

Prints the 11th column, which is the command name/path.
ps aux | awk '{print $11}'

ubuntu:~$ ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.1  0.6  22096 13152 ?        Ss   04:39   0:01 /sbin/init

Prints only the header row of ps aux.
ps aux | head -1

chevron-rightCPU/DISK/MEMORY THreshouldhashtag

#!/bin/bash

# Set threshold
THRESHOLD=80

# Set email address to send alerts
EMAIL="[email protected]"

# ---------------- CPU CHECK ----------------
CPU_IDLE=$(top -bn1 | grep "Cpu(s)" | awk '{print $8}' | cut -d'.' -f1)
CPU_USAGE=$((100 - CPU_IDLE))

# ---------------- MEMORY CHECK ----------------
MEM_TOTAL=$(free -m | grep Mem | awk '{print $2}')
MEM_USED=$(free -m | grep Mem | awk '{print $3}')
MEM_USAGE=$((MEM_USED * 100 / MEM_TOTAL))

# ---------------- DISK CHECK ----------------
DISK_USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')

# ---------------- PRINT STATUS ----------------
echo "CPU Usage:    $CPU_USAGE%"
echo "Memory Usage: $MEM_USAGE%"
echo "Disk Usage:   $DISK_USAGE%"

# ---------------- ALERTS ----------------
ALERT_MSG=""

if [ "$CPU_USAGE" -ge "$THRESHOLD" ]; then
  ALERT_MSG+="CPU usage is above $THRESHOLD% (Current: $CPU_USAGE%)\n"
fi

if [ "$MEM_USAGE" -ge "$THRESHOLD" ]; then
  ALERT_MSG+="Memory usage is above $THRESHOLD% (Current: $MEM_USAGE%)\n"
fi

if [ "$DISK_USAGE" -ge "$THRESHOLD" ]; then
  ALERT_MSG+="Disk usage is above $THRESHOLD% (Current: $DISK_USAGE%)\n"
fi

# ---------------- SEND MAIL ----------------
if [ -n "$ALERT_MSG" ]; then
  echo -e "$ALERT_MSG" | mail -s "⚠️ System Resource Alert" "$EMAIL"
  echo "⚠️ Alert sent to $EMAIL"
else
  echo "✅ All resources are under $THRESHOLD%"
fi

Last updated