Interview Scripting (Bash, Groovy)

What are exit codes you should use, and what does a non-zero exit signal to a pipeline? [Intermediate]

Answer

I use 0 for success and nonzero for failure. Common conventions are 1 for general failure, 2 for bad usage, 126 for found but not executable, 127 for command not found, and 128+n for termination by signal n. Pipelines and CI use nonzero status to stop or mark the step as failed.

Technical explanation

Document custom exit codes when scripts are called by automation or other teams.

Do not return arbitrary large numbers because shell statuses wrap to 0-255.

When wrapping a command, preserve its exit code if callers need the exact failure reason.

Hands-on example

usage() { echo "usage: $0 -f file" >&2; exit 2; }

[[ $# -gt 0 ]] || usage

some_command "$@"

rc=$?

if (( rc != 0 )); then

echo "some_command failed with rc=$rc" >&2

exit "$rc"

fi

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions