NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Middle0 views

How can you check the exit status of a bash script? What exit code does an unsuccessful script return, and why?

Practice

Asked at

AI answer

The exit code of the last command run can be checked using $?; check it immediately, because the next command overwrites the value:

./script.sh
status=$?
printf 'exit code: %d\n' "$status"

Success is usually indicated by code 0, and failure by any nonzero code. There is no universal error code: 1 is often used as a general error, while specific values may have special meanings. A script exits with the code of the last command run unless exit N is called; therefore, a failure in an intermediate command does not by itself guarantee a nonzero final exit code. You can check with if ./script.sh; then ...; else ...; fi. set -e can terminate a script when a command fails, but it has exceptions and subtleties, so critical errors are more reliably handled explicitly.