🐧 Linux / Shell Scripting
Intermediate
What is $? and how does exit status error handling work in bash?
Answer
$? holds the exit status of the last executed command — 0 means success, any non-zero value (1–255) indicates an error. Check it immediately after a command: cp src dst; if [ $? -ne 0 ]; then echo "copy failed"; exit 1; fi. Short-circuit operators provide concise handling: command || exit 1 (exit on failure), command && next_command (run next only if first succeeds). Set set -e at the top of a script to exit automatically on any unhandled error. Use exit N to terminate a script with a specific code. CI/CD systems check the script's exit code to determine pass/fail.