Interview Prep/Shell Scripting/Troubleshooting: strict mode, exit codes, pipelines and traps

A check `procs=$(ps aux | grep -v grep | grep -c '[n]ginx: worker')` kills the script under `set -euo pipefail` whenever nginx is down, before the alert code runs.

IntermediateTroubleshootingTroubleshooting: strict mode, exit codes, pipelines and traps
Answer

Likely causes → grep exits 1 when it matches nothing, and grep -c exits 1 even while printing 0. With pipefail the pipeline fails, the assignment inherits that status, and set -e exits, so the "nginx is down" branch is never reached. "No match" is not an error here, but strict mode cannot know that.

Diagnose →

echo foo | grep -c bar; echo "rc=$?"      # prints 0, rc=1

Fix → Tell the shell that "no match" is an expected outcome, or use a tool that does not treat it as failure:

procs=$(pgrep -c -f 'nginx: worker' || true)        # pgrep exits 1 on no match too
procs=$(ps -eo args | awk '/^nginx: worker/ {n++} END {print n+0}')   # awk exits 0 either way
if (( procs == 0 )); then alert CRITICAL "nginx has no workers"; fi

Avoid || true on a whole long pipeline, because it also hides real failures such as ps itself breaking.

Prevent → Treat grep, diff, cmp and pgrep as "exit 1 is a valid answer" tools and handle that status explicitly.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: strict mode, exit codes, pipelines and traps