typestar

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

  1. $? holds the last command's status.
  2. && runs on success, || on failure — inline control flow.
  3. A function's (( )) result is its exit code, ready for chaining.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Conditionals, step 6 of 26 in Language basics.

← Previous Next →