Exit code

2 snippets across 2 stacks - Bash & Linux, Docker

SHBash & Linux

Exit Codes & Error Handling

SH · Bash Scripting
Syntax
$?
set -e
set -o pipefail
command || handle_error
Example
#!/usr/bin/env bash
set -euo pipefail

grep -q 'ready' status.txt || { echo 'Not ready'; exit 1; }

if ! deploy_app; then
  echo "Deploy failed with code $?"
  rollback
  exit 1
fi

Note $? holds the exit code of the last command (0 = success, non-zero = failure). set -e aborts the script on any non-zero exit. set -u treats unset variables as errors. set -o pipefail catches failures in piped commands. Always use all three in production scripts.

DKDocker

Wait for Container to Stop

DK · Containers
Syntax
docker wait <container>
Example
docker wait batch-job && echo 'Job finished'
Output
0

Note Blocks until the container stops and then prints the exit code. Exit code 0 means success. Useful in scripts that need to wait for a task container to finish before proceeding.

Frequently asked questions

How do you exit code?
This task is covered in 2 stacks on this page: Bash & Linux, Docker. The "Exit Codes & Error Handling" snippet in Bash & Linux uses `$?`.
Which command does the Bash & Linux example use?
The "Exit Codes & Error Handling" snippet uses `$?`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "exit code" on this page?
Bash & Linux, Docker. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Exit Codes & Error Handling": $? holds the exit code of the last command (0 = success, non-zero = failure). set -e aborts the script on any non-zero exit. set -u treats unset variables as errors. set -o pipefail catches failures in piped commands. Always use all three in production scripts.