Every command returns an exit status (0 = success, non-zero = failure). Scripts and CI pipelines use exit codes to decide whether a deploy should continue.
Checking status
ls /tmp
echo "status: $?"
ls /nonexistent 2>/dev/null
echo "status: $?"$? holds the last command's exit code—read it immediately before another command runs.
Explicit return
#!/usr/bin/env bash
if [[ $# -lt 1 ]]; then
echo "usage: $0 name" >&2
exit 1
fi
echo "Hello, $1"
exit 0Send errors to stderr with >&2 so stdout stays machine-readable.
Logical operators
false && echo "won't run"
true || echo "won't run"
false || echo "runs because previous failed"&& and || short-circuit like many languages—common in CI one-liners.
Important interview questions and answers
- Q: What exit code means success?
A: 0—by Unix convention. - Q: Why check $? quickly?
A: Another command overwrites $? immediately.
Self-check
- What does $? contain?
- What exit code does false typically return?
Tip: In CI, non-zero exits fail the job—always check $? when not using set -e.
Interview prep
- Success code?
0 by convention.
- $? meaning?
Exit status of the last foreground command.