Logging, usage messages and exit codes

Intermediate · 7 min

Make a script behave like a real command: usage text, messages on stderr, a small log function, and exit codes that mean something. Run on Bash 5.3.

Before thisExit status and && / || listsstdin, stdout and stderrParsing options with getoptsStructure and style: main functions and shfmtSafe temporary files and atomic writes

You Suck at Programming · 7 min

Logging, usage messages and exit codes

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by You Suck at ProgrammingReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Results go to standard output and everything about the run (progress, warnings, errors, usage on a mistake) goes to standard error, so a pipeline or redirect receives only data.
  • Print usage and exit 0 for -h. Print usage to stderr and exit nonzero for a usage mistake. Convention (sysexits.h) uses 64 for command-line usage errors, and 2 is also common.
  • A tiny log function that writes a timestamp, the program name and a message to stderr, plus a die helper that logs and exits, replaces scattered echo >&2 lines.
  • Exit 0 only for success. Use a nonzero code when anything the caller asked for failed, even if the script continued, so callers can tell. Codes are 0-255: 256 wraps to 0.
  • 126 (not executable), 127 (not found) and 128+n (killed by signal n) are the shell's own, so avoid reusing them for your own meanings.

A script is a command

When you run grep wrongly it prints a usage line and exits nonzero. grep -h prints help and exits 0. Its results go to standard output and its complaints to standard error. Other programs can rely on all of that without reading its source.

Your scripts become commands too, run by cron, CI jobs and colleagues, and they get used in the same ways: piped, redirected, and checked with &&. So give them the same manners. That comes down to three things: say how to use the script, keep data and chatter on separate streams, and exit with a status that is true.

I wrote a small script, count500.sh, and ran every case below on macOS with Bash 5.3. It is shfmt- and ShellCheck-clean.

The script

#!/usr/bin/env bash
# count500.sh - count HTTP 500 responses in access logs.
set -euo pipefail

readonly PROG=${0##*/}
readonly EX_USAGE=64 # sysexits.h: command line usage error
VERBOSE=0

usage() {
  cat <<USAGE
Usage: $PROG [-v] [-h] LOGFILE...

Count lines with HTTP status 500 in each LOGFILE.

  -v  log progress to stderr
  -h  show this help and exit
USAGE
}

log() { printf '%s %s: %s\n' "$(date +%H:%M:%S)" "$PROG" "$*" >&2; }
debug() { if ((VERBOSE)); then log "debug: $*"; fi; }
die() {
  local code=$1
  shift
  log "error: $*"
  exit "$code"
}

main parses options with getopts: -h prints usage and exits 0, and an unknown option or a missing file list calls usage >&2 and then die "$EX_USAGE" .... For each file it checks readability, logs a warning and keeps going if it cannot read it, and prints count<TAB>filename for the rest. It ends with return "$status", where status is 1 if any file failed.

The usage text uses a here document. $PROG comes from $0, so the help always shows the name the user actually typed.

Running it

$ ./count500.sh fx/logs/access.log
24	fx/logs/access.log
exit=0
$ ./count500.sh -h
Usage: count500.sh [-v] [-h] LOGFILE...
...
exit=0
$ ./count500.sh
Usage: count500.sh [-v] [-h] LOGFILE...
...
10:25:17 count500.sh: error: no files given
exit=64
$ ./count500.sh -x fx/logs/access.log
...
10:25:17 count500.sh: error: unknown option -x
exit=64

Asking for help is not an error, so -h exits 0. Misusing the command is, so the usage text goes to stderr and the status is nonzero. I used 64, the “command line usage error” value from the BSD sysexits.h convention. 2 is just as common, and what matters is picking one and sticking to it.

Partial failure is still failure

One good file and one bad:

$ ./count500.sh nope fx/logs/access.log; echo "exit=$?"
10:25:17 count500.sh: warning: cannot read nope
24	fx/logs/access.log
exit=1

The script did what it could, but a caller who asked for two files and got one answer needs to know. Exit 0 here would be a lie that a calling script’s && would believe. This is the exit status idea turned around: you are now the one setting it.

Two streams, kept apart

The reason for all the >&2: results and chatter must be separable. With -v, the progress lines and warnings are on stderr and the table is on stdout:

$ ./count500.sh -v nope fx/logs/access.log 2>/dev/null
24	fx/logs/access.log
---
$ ./count500.sh -v nope fx/logs/access.log >/dev/null
10:25:17 count500.sh: warning: cannot read nope
10:25:17 count500.sh: debug: counting fx/logs/access.log

So ./count500.sh logs/* | sort -rn sorts only data, while warnings still reach a human. This is the streams lesson put to work. To keep a copy of the log as well as show it, stderr can go through tee using process substitution:

$ ./count500.sh -v fx/logs/access.log 2> >(tee run.log >&2) >/dev/null
10:25:17 count500.sh: debug: counting fx/logs/access.log
$ wc -l < run.log
       1

Log lines carry a time of day here. For logs that others read, a full date, ideally in UTC (date -u +%Y-%m-%dT%H:%M:%SZ printed 2026-11-23T04:55:17Z), avoids ambiguity. A system logger is also on this Mac (/usr/bin/logger), which sends a line to syslog. I did not run it, since it writes to the system log.

Exit codes you should not reuse

The shell already assigns meanings to some numbers, and I produced each:

$ ./nonexistent; echo "command not found -> $?"
command not found -> 127
$ ./noexec.sh; echo "not executable -> $?"
not executable -> 126
$ sleep 5 & kill -TERM $!; wait $!; echo "SIGTERM -> $?"
SIGTERM -> 143

127 is “not found”, 126 is “found but cannot execute”, and 128+n means killed by signal n, as in the signals lesson. A custom code that collides with these confuses whoever reads it. Also, a status is one byte:

$ bash -c 'exit 256'; echo $?
0
$ bash -c 'exit 257'; echo $?
1

So exit 256 reports success, which has caused real bugs when an error count is used as the exit code. Clamp it: exit $((n > 255 ? 255 : n)), or use a small fixed set (0 success, 1 failure, 64 usage) and document it in usage.

What to keep

Usage text on -h and on misuse. Data on stdout, everything else on stderr. One log and one die. A status that is nonzero whenever something failed. In a longer-running script, add a -v/-q pair so logs can be turned up or down. A cleanup trap from the traps lesson should keep the original status. Bash’s $? inside an EXIT trap is the status the script was already leaving with.

About the video

“Exit Codes in Bash explained! Some gotchas and pitfalls with them.” is a 6-minute 40-second video from You Suck at Programming (Dave Eddy), published July 2025. The description is only links and credits, with no chapters, and I could not read a transcript, so I am going by the title. It covers exit codes only. I found no video that covers usage messages, logging and exit codes together, so the usage and logging parts of this lesson have no video behind them. It is in English. Learn Linux TV’s longer exit-code video, whose chapters run from what exit codes are through checking $? to ordering and manipulating them, is linked under deeper.

Where this fits

A script with a clear contract is a script you can test. The last lesson does that with Bats: testing scripts with Bats.

Check yourself

  1. 01Why should a usage error message go to stderr rather than stdout?

    stdout is for the script's data. If someone pipes it into another command, a usage message on stdout would be read as data. stderr stays visible on the terminal.

  2. 02A script processes three files, one of which is unreadable. It prints results for the other two. What should its exit status be?

    Nonzero, such as 1. It did not do everything the caller asked, and callers use the status to know. The results for the two good files can still be printed.

  3. 03What happens if you write exit 256?

    The status is 0, because exit codes are taken modulo 256. exit 257 gives 1. Keep your codes between 1 and 255.

  4. 04Why avoid exit 127 as a custom code for 'config missing'?

    The shell uses 127 for 'command not found', so a caller reading the status would misdiagnose the failure. Pick codes that the shell does not already use.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark