Exit codes in Bash
Zero is success, everything else is failure, and && || route on it.
# every command leaves a status in $?; zero means success
true
echo "true exited with $?"
false || echo "false failed, so || ran this"
# && chains on success, || on failure
mkdir -p /tmp/ts_demo && echo "created" || echo "could not create"
# a function's return value is its exit code
is_even() { (( $1 % 2 == 0 )); }
is_even 4 && echo "4 is even"
is_even 7 || echo "7 is not"
rmdir /tmp/ts_demo
How it works
$?holds the last command's status.&&runs on success,||on failure — inline control flow.- A function's
(( ))result is its exit code, ready for chaining.
Keywords and builtins used here
echofalsetrue
The run, in numbers
- Lines
- 13
- Characters to type
- 397
- Tokens
- 50
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 35 seconds.
Step 3 of 3 in Conditionals, step 6 of 26 in Language basics.