Writing Useful Error Messages
An error message is the only part of a script that is written specifically for the moment something has gone wrong. The person reading it may be you six months from now, a colleague who has never opened the script, or someone scrolling through a CI log at night. A useful message answers their questions immediately: which program complained, what it was trying to do, what exactly was wrong, and, when possible, what to do about it. A message like Error! or failed answers none of them and sends the reader into the source code.
This lesson covers where error messages should go, the conventional format on Unix-like systems, what information to include, and the small helper functions that keep messages consistent across a script.
Send Errors to Standard Error
Every process has two output streams (lesson 56): standard output for results and standard error for diagnostics. Error and warning messages belong on standard error, which a Bash script reaches with >&2:
echo "result line"
echo "s.sh: warning: cache is stale" >&2
Running the script with its output redirected to a file:
bash s.sh > out.txt
cat out.txt
s.sh: warning: cache is stale
result line
The warning appeared on the terminal while the file received only the result. This separation is what makes scripts composable. When the output is piped into another command or saved to a file, messages do not end up mixed into the data, and the person running the command still sees them. Usage text that the user explicitly asked for with --help is the exception: it is the requested output, so it goes to standard output (the complete example below shows both cases).
Follow the Conventional Format
Standard tools on Linux share a recognizable message style:
ls: cannot access '/nonexistent': No such file or directory
cp: missing destination file operand after 'a'
Try 'cp --help' for more information.
grep: nofile: No such file or directory
mkdir: cannot create directory '/proc/x': No such file or directory
The pattern is program: what went wrong: why. The program name comes first because, in a pipeline or a long log, several programs write to the same terminal, and the reader needs to know which one is speaking. The object of the action, a file name for example, is usually quoted. The final part is often the operating system's own explanation, such as No such file or directory.
Your scripts become easier to read alongside these tools if they use the same style.
Getting the Script's Name
$0 holds the name the script was started with, which depends on how it was called. ${0##*/} removes everything up to the last slash (lesson 54) and leaves just the file name:
echo "\$0=[$0] \${0##*/}=[${0##*/}]"
Run three different ways:
$0=[name.sh] ${0##*/}=[name.sh]
$0=[./name.sh] ${0##*/}=[name.sh]
$0=[/home/user/project/name.sh] ${0##*/}=[name.sh]
Storing it once at the top, as prog=${0##*/}, gives every message the same prefix.
Say What, Which and Why
Compare two messages for the same failure:
copy failed
could not archive 'report.txt' to '/proc/archive/'; the original was not changed
The first says something went wrong. The second says what the script was trying to do (archive), which objects were involved (both paths), and what state the system is in now (nothing was lost). A good message usually contains:
- The action the script was performing, in the user's terms: "archive the report", not "cp returned 1".
- The specific values involved: the file name, the host, the setting.
- The reason, if known: the operating system's error, the rule that was broken, or the value that was expected.
- The consequence or next step, when it is not obvious: "nothing was changed", "run with --force to overwrite", "see 'prog --help'".
Keep the Command's Own Message
Many commands already print a precise reason. Hiding it with 2>/dev/null and replacing it with a vague message throws information away. This script tries to copy a file that does not exist three times, with three different approaches:
prog=${0##*/}
src=report.txt; dest=/proc/archive/
if ! cp -- "$src" "$dest" 2>/dev/null; then
echo "$prog: error: copy failed" >&2
fi
if ! cp -- "$src" "$dest"; then
echo "$prog: error: could not archive '$src' to '$dest'; the original was not changed" >&2
fi
if ! err=$(cp -- "$src" "$dest" 2>&1); then
echo "$prog: error: archiving '$src' failed: ${err#cp: }" >&2
fi
keep.sh: error: copy failed
cp: cannot stat 'report.txt': No such file or directory
keep.sh: error: could not archive 'report.txt' to '/proc/archive/'; the original was not changed
keep.sh: error: archiving 'report.txt' failed: cannot stat 'report.txt': No such file or directory
The first version hides the real reason: the reader cannot tell whether the source was missing or the destination was not writable. The second lets cp explain why and adds a line saying what the failure means for the script. The third captures the command's message into a variable and folds it into one line; ${err#cp: } removes cp's own prefix so the line does not name two programs. The second form is the simplest and is usually enough; the third is useful when every message must follow one format, for example in a log file.
Show Values So That Problems Are Visible
Empty strings and trailing spaces are invisible in a message, and they are a common cause of errors:
v1=""; v2="report.txt "; v3=$'a\tb'
echo "error: cannot open $v1"
echo "error: cannot open '$v1'"
echo "error: cannot open $v2(end)"
echo "error: cannot open '$v2'"
printf 'error: cannot open %q\n' "$v1" "$v2" "$v3"
error: cannot open
error: cannot open ''
error: cannot open report.txt (end)
error: cannot open 'report.txt '
error: cannot open ''
error: cannot open report.txt\
error: cannot open $'a\tb'
Without quotes, the empty name produced a message that seems to have been cut off, and the trailing space in report.txt was impossible to see. Wrapping the value in single quotes inside the message makes both obvious. printf %q (lesson 47) goes further: it prints the value in a form that could be pasted back into the shell, which also reveals tabs and other control characters as $'a\tb'.
Print Messages with printf '%s'
Values in messages come from users, files and other commands, so they can contain anything. Two problems appear when such values are printed carelessly:
val="-n"
echo "$val"
echo "[after echo -n]"
printf '%s\n' "$val"
val='50%d'
printf "value: $val\n"
printf 'value: %s\n' "$val"
[after echo -n]
-n
value: 500
value: 50%d
echo "$val" printed nothing at all, because echo read -n as its own option. Putting the value into printf's format string made %d a format directive, so 50%d became 500. The reliable form keeps the format string fixed and passes values as arguments: printf 'format %s\n' "$value" (lesson 30). The helper functions in this lesson use that form.
Helper Functions: warn and die
Writing >&2, the program name and an exit on every failure path is repetitive and easy to get inconsistent. Two small functions solve this:
prog=${0##*/}
warn() { printf '%s: warning: %s\n' "$prog" "$*" >&2; }
die() { printf '%s: error: %s\n' "$prog" "$*" >&2; exit 1; }
warn "config file not found, using defaults"
[[ -d /nonexistent ]] || die "output folder '/nonexistent' does not exist"
echo "not reached"
dw.sh: warning: config file not found, using defaults
dw.sh: error: output folder '/nonexistent' does not exist
The script ended with status 1. "$*" joins all arguments with spaces, so die "cannot open" "$file" and die "cannot open $file" both work. The warning: and error: labels tell the reader whether the script continued.
When different failures deserve different exit codes, die can accept an optional status as its first argument:
die() {
local status=1
if [[ $1 =~ ^[0-9]+$ ]]; then status=$1; shift; fi
printf '%s: error: %s\n' "$prog" "$*" >&2
exit "$status"
}
die 3 "database unreachable"
ds.sh: error: database unreachable
The script ended with status 3. Whatever codes a script uses, document them and use them consistently; a common minimum is 0 for success, 1 for errors and 2 for incorrect usage (lesson 116).
die Inside $( ) Ends Only the Subshell
exit inside a command substitution leaves only the subshell (lesson 118). A function that calls die and is used inside $( ) prints its message, but the script continues:
die() { echo "error: $*" >&2; exit 1; }
get_port() { [[ -r app.conf ]] || die "cannot read app.conf"; echo 8080; }
port=$(get_port)
echo "script continued, port=[$port]"
port=$(get_port) || exit
echo "not reached"
error: cannot read app.conf
script continued, port=[]
error: cannot read app.conf
The second assignment adds || exit, which ends the main script with the substitution's status (1 here). The message has already been printed by die, so exit needs no message of its own. Under set -e, the failed assignment stops the script without || exit (lesson 119).
Adding Location Information
For errors that indicate a bug in the script rather than bad input, the line number and function name help the developer find the problem. Bash provides them in arrays: FUNCNAME lists the active functions, and BASH_LINENO holds the line from which each one was called:
die() {
printf '%s: error: %s (line %s in %s)\n' "${0##*/}" "$1" "${BASH_LINENO[0]}" "${FUNCNAME[1]:-main}" >&2
exit 1
}
load() {
[[ -r $1 ]] || die "cannot read '$1'"
}
load settings.ini
loc.sh: error: cannot read 'settings.ini' (line 6 in load)
Inside die, FUNCNAME[0] is die itself, FUNCNAME[1] is the function that called it, and BASH_LINENO[0] is the line of that call (line 6, inside load). At the top level of the script FUNCNAME[1] is unset, so :-main provides a label. The caller builtin returns similar information in one line; caller 0 inside a function show called from outer on line 2 printed 2 outer caller.sh.
Location details are for developers. For mistakes the user can fix, such as a missing file or a bad option, a clear description of the input problem is more useful than a line number in the script. The ERR trap of lesson 121 is a good way to add location information to unexpected failures without cluttering every message.
Colors, Only Where They Help
Colored output can make errors easier to spot in a terminal, but escape codes become garbage characters in log files and in CI systems that do not interpret them. Test whether standard error is a terminal with -t 2 (lesson 72) and use colors only then:
if [[ -t 2 ]]; then red=$'\e[31m'; reset=$'\e[0m'; else red=; reset=; fi
printf '%serror:%s disk full\n' "$red" "$reset" >&2
With standard error sent into a pipe, od -c showed plain text:
0000000 e r r o r : d i s k f u l l
0000020 \n
Run under a pseudo-terminal with the script command, the same line contained the escape sequences (033 [ 3 1 m before error: and 033 [ 0 m after it). Many tools also skip colors when the NO_COLOR environment variable is set, a convention a script can follow by adding [[ -n ${NO_COLOR-} ]] to the same test.
Never Put Secrets in Messages
Error messages are copied into logs, tickets and chat messages. A message such as login failed for token abc123... leaks the credential to everyone who sees it. Name the setting instead of printing its value, for example API_TOKEN was rejected by the server, and if a hint is needed, show only harmless facts such as whether the variable is empty or how long it is. Lesson 158 covers handling secrets in scripts.
A Complete Example
This validator checks a key=value configuration file. It applies the ideas of this lesson together: a usage message with exit status 2, die for problems that make further checking pointless, and a file:line: message format for problems inside the file, the same format compilers and linters use, which many editors can turn into clickable links. Instead of stopping at the first problem, it reports all of them, so the user can fix the file in one pass.
#!/usr/bin/env bash
# check-config.sh FILE: validate a key=value configuration file
prog=${0##*/}
usage() { printf 'usage: %s FILE\n' "$prog"; }
die() { printf '%s: error: %s\n' "$prog" "$*" >&2; exit 1; }
if (( $# != 1 )); then
usage >&2
printf "Try '%s --help' for more information.\n" "$prog" >&2
exit 2
fi
if [[ $1 == --help ]]; then
usage
echo "Checks that port, log_dir and mode are set to valid values."
exit 0
fi
file=$1
[[ -e $file ]] || die "'$file' does not exist"
[[ -f $file ]] || die "'$file' is not a regular file"
[[ -r $file ]] || die "'$file' is not readable"
errors=0
problem() { # problem LINE MESSAGE (LINE may be empty for whole-file problems)
printf '%s:%s %s\n' "$file" "${1:+$1:}" "$2" >&2
errors=$((errors + 1))
}
declare -A seen=()
lineno=0
while IFS= read -r line || [[ -n $line ]]; do
lineno=$((lineno + 1))
[[ -z $line || $line == \#* ]] && continue
if [[ $line != *=* ]]; then
problem "$lineno" "expected key=value, found '$line'"
continue
fi
key=${line%%=*}
value=${line#*=}
seen[$key]=$lineno
case $key in
port)
if [[ ! $value =~ ^[0-9]+$ ]] || (( 10#$value < 1 || 10#$value > 65535 )); then
problem "$lineno" "port must be a number from 1 to 65535, got '$value'"
fi ;;
log_dir)
[[ -d $value ]] || problem "$lineno" "log_dir '$value' is not an existing directory" ;;
mode)
case $value in
dev|prod) ;;
*) problem "$lineno" "mode must be 'dev' or 'prod', got '$value'" ;;
esac ;;
*)
problem "$lineno" "unknown key '$key' (allowed: port, log_dir, mode)" ;;
esac
done < "$file"
for required in port log_dir mode; do
[[ -n ${seen[$required]-} ]] || problem "" "required key '$required' is missing"
done
if (( errors > 0 )); then
printf '%s: %d problem(s) found in %s\n' "$prog" "$errors" "$file" >&2
exit 1
fi
echo "$file: OK"
The test files: good.conf with valid settings; partial.conf containing only port=8080; and bad.conf:
# app settings
port=80800
log_dir=/var/log/myap
mode=production
timeout 30
colour=blue
The mode line in bad.conf ends with a space.
./check-config.sh; echo "status $?"
./check-config.sh --help; echo "status $?"
./check-config.sh good.conf; echo "status $?"
./check-config.sh bad.conf; echo "status $?"
./check-config.sh partial.conf; echo "status $?"
./check-config.sh missing.conf; echo "status $?"
./check-config.sh logs; echo "status $?"
usage: check-config.sh FILE
Try 'check-config.sh --help' for more information.
status 2
usage: check-config.sh FILE
Checks that port, log_dir and mode are set to valid values.
status 0
good.conf: OK
status 0
bad.conf:2: port must be a number from 1 to 65535, got '80800'
bad.conf:3: log_dir '/var/log/myap' is not an existing directory
bad.conf:4: mode must be 'dev' or 'prod', got 'production '
bad.conf:5: expected key=value, found 'timeout 30'
bad.conf:6: unknown key 'colour' (allowed: port, log_dir, mode)
check-config.sh: 5 problem(s) found in bad.conf
status 1
partial.conf: required key 'log_dir' is missing
partial.conf: required key 'mode' is missing
check-config.sh: 2 problem(s) found in partial.conf
status 1
check-config.sh: error: 'missing.conf' does not exist
status 1
check-config.sh: error: 'logs' is not a regular file
status 1
What makes these messages useful:
- Every problem points to its place.
bad.conf:3:tells the user which line to open. Problems that belong to the whole file, such as a missing key, have no line number, and the${1:+$1:}expansion leaves the line part out for them. - Every problem states the rule and the actual value.
got 'production 'shows the trailing space that would otherwise be invisible, andallowed: port, log_dir, modereveals thatcolouris a spelling issue rather than an unsupported feature. - Messages and results are on separate streams. All problems go to standard error, so
./check-config.sh bad.conf 2>/dev/nullprinted nothing, while its exit status, 1, still reported the failure. TheOKline and the--helptext go to standard output because they are the requested output. - Exit codes are consistent. 0 for a valid file or for
--help, 1 for problems with the file, 2 for wrong usage, following the convention thatTry '... --help'messages in GNU tools also use. - The checks on the file itself come first. "Does not exist", "is not a regular file" and "is not readable" each produce a different message. A single "cannot read file" would leave the user guessing which of the three it was.
- Numbers are checked as decimal.
10#$valuemakes a value such as0800count as 800 instead of being rejected as an invalid octal number (lesson 73). A test file withport=0800was accepted, andport=0was reported as out of range.
The examples were run with Bash 5.2.21, GNU coreutils 9.4 and util-linux script on Ubuntu 24.04.