In a Bash script, how do you check whether a command succeeded, and how would you make the script stop on the first error?
technical-conceptual · Junior level · software-engineering
What the interviewer is really asking
Assesses whether the candidate writes defensive scripts that fail loudly rather than silently continuing past errors.
What to say
- Explain exit status: every command sets $? to 0 on success and non-zero on failure, and you can branch on it directly with if mycommand; then ... since if tests the exit code.
- Reach for set -e (errexit) to make the script abort on the first failing command, and pair it with set -o pipefail so a failure anywhere in a pipeline isn't masked by the last command's success.
- Mention set -u to catch unset variables, so the common safe-script header is set -euo pipefail, and note you can still handle expected failures explicitly when you don't want to abort.
What to avoid
- Saying you just read the output text on screen to tell whether a command worked.
- Claiming a script always stops on its own when something fails, with no mention of set -e or exit codes.
- Thinking a non-zero exit code means success because zero looks like a falsy value.
Example answers
Strong: Each command sets $?: zero means success, anything non-zero means failure, and if/then tests that exit code directly so I can write if curl ...; then. To make a whole script bail on the first error I put set -euo pipefail at the top: -e stops on any failing command, pipefail surfaces failures mid-pipeline instead of trusting the last command, and -u catches typos in variable names. When I expect a command might fail, I handle it explicitly so it doesn't trip the abort.
Weak: You can usually tell a command worked by looking at whether it printed an error message. If it printed something red or said error, it failed. Bash scripts stop by themselves when there's a problem, so I don't really do anything special, I just run the commands one after another.