Displaying Helpful Messages in Scripts
A script talks to its user through the messages it prints. Good messages tell the person what is happening, what went wrong, and what to do next. Poor messages leave them guessing. Bash gives you the tools to print text, send it to the right output channel, format it neatly, and even add color, and this lesson shows how to use them together.
Two Output Channels
Every Unix process starts with two output channels:
- Standard output (file descriptor 1) carries the normal results of a program.
- Standard error (file descriptor 2) carries diagnostics, warnings, and error messages.
On a terminal both appear on the screen, so they look the same. The difference matters as soon as the output is redirected. If a user runs ./report.sh > report.txt, the results go into the file, but the error messages should still appear on the screen, so the user notices a problem. Mixing the two would put error text inside the report.
To send a message to standard error, redirect it with >&2, which means "send this output to file descriptor 2":
echo "This is a normal message"
echo "This is an error message" >&2
The redirection can be written at the end of the command, or at the start, as in >&2 echo "message". Both forms behave the same way:
echo "to stderr, form 1" >&2
>&2 echo "to stderr, form 2"
Redirection has its own lessons later in this tutorial, so for now remember one rule: informational output goes to standard output, and problems go to standard error.
Messages with echo and printf
The previous lesson covered echo and printf. Two details matter for messages.
echo -n suppresses the final newline, which lets you print a status word on the same line as the text before it:
echo -n "Working... "
echo "done"
Working... done
printf is better when you need alignment, because its format string controls the width of each column. In %-10s, the minus sign left-aligns the text in a field ten characters wide; in %5d the number is right-aligned in five characters:
printf '%-10s %5s\n' 'Name' 'Size'
printf '%-10s %5d\n' 'a.txt' 120 'b.txt' 45
Name Size
a.txt 120
b.txt 45
When printf receives more arguments than its format uses, it reuses the format, which is why both file lines above come from a single command.
A horizontal line can be built with printf and a parameter expansion that replaces spaces with another character:
line=$(printf '%*s' 30 '')
echo "${line// /=}"
==============================
The * in %*s takes the field width (30) from the next argument, so the command produces 30 spaces. The expansion ${line// /=} then replaces every space with =.
Writing Small Message Functions
If a script prints many messages, repeating printf and >&2 everywhere gets tedious. A short function for each kind of message keeps the script readable and makes it easy to change the format later.
info() { printf 'INFO: %s\n' "$*"; }
warn() { printf 'WARNING: %s\n' "$*" >&2; }
error() { printf 'ERROR: %s\n' "$*" >&2; }
info "Starting backup"
warn "Disk is 85% full"
error "Cannot open the destination"
Running this script in a terminal prints:
INFO: Starting backup
WARNING: Disk is 85% full
ERROR: Cannot open the destination
Each function uses $*, which joins all of its arguments into one string, and printf '%s\n' prints it safely. Using printf with a %s placeholder, instead of putting the message in the format string, means characters such as % or backslashes in the message are printed literally rather than interpreted. Functions are explained in detail in a later lesson, so here you only need to know that the text inside the braces runs each time the function name is used.
The warn and error functions send their output to standard error. You can see the difference by hiding one channel:
./messages.sh 2>/dev/null
INFO: Starting backup
Redirecting channel 2 to /dev/null (a special file that discards everything) hid the warning and error lines, and only the information message remained.
Adding a Timestamp
Messages from scripts that run unattended are far more useful when they say when they were printed. The date command supplies the time:
log() {
printf '%s [%s] %s\n' "$(date +%H:%M:%S)" "$1" "$2"
}
log INFO "started"
log ERROR "disk full"
14:32:07 [INFO] started
14:32:07 [ERROR] disk full
The time shown on your machine will differ. The $(date +%H:%M:%S) part is command substitution: Bash runs date, with the format hours:minutes:seconds, and puts its output into the message. The first argument ($1) is the level, and the second ($2) is the text.
Stopping with a Clear Error
When a script cannot continue, it should say why and then stop with a non-zero exit status, so that other programs can tell it failed. A helper function combines both steps:
die() {
printf 'ERROR: %s\n' "$1" >&2
exit "${2:-1}"
}
die "config file is missing" 3
echo "this line is never reached"
ERROR: config file is missing
Checking the exit status afterwards with echo $? shows 3. The expression ${2:-1} means "use the second argument, or 1 if there is none", so the exit status is optional for callers. Exit codes are covered in depth in a later lesson.
Printing Usage Instructions
When a user runs a script incorrectly, the most helpful reply explains the correct form. The ${0##*/} expansion removes everything up to the last slash from $0 (the name used to start the script), leaving only the file name, so the message always shows the real script name.
A here document (<<), which feeds a block of text to a command, is a clean way to print several lines. Here documents get their own lesson later, so this example only previews the idea. The complete script below reads a file and prints the number of lines it contains:
#!/usr/bin/env bash
script_name=${0##*/}
info() { printf 'INFO: %s\n' "$*"; }
error() { printf 'ERROR: %s\n' "$*" >&2; }
usage() {
cat <<USAGE
Usage: $script_name FILE
Counts the lines in FILE and prints the result.
USAGE
}
if [ "$#" -ne 1 ]; then
error "exactly one argument is required"
usage >&2
exit 2
fi
if [ ! -r "$1" ]; then
error "cannot read '$1'"
exit 1
fi
info "Counting lines in $1"
lines=$(wc -l < "$1")
info "Found $lines lines"
The script is saved as msg.sh, and a three-line file called data.txt is used for the test. Running it with the right arguments produces:
INFO: Counting lines in data.txt
INFO: Found 3 lines
The exit status is 0. Running it with no arguments shows the usage message:
ERROR: exactly one argument is required
Usage: msg.sh FILE
Counts the lines in FILE and prints the result.
The exit status here is 2, and every line of that output went to standard error, because both error and usage >&2 write there. Running it with a file that does not exist gives:
ERROR: cannot read 'nope.txt'
with exit status 1. If the user redirects standard output to a file, as in ./msg.sh nope.txt > out.log, the error still appears on the screen and out.log stays empty, which is exactly the behavior the user expects.
Here is how the script works, step by step:
"$#"holds the number of arguments. The test[ "$#" -ne 1 ]is true when the count is not one.[ ! -r "$1" ]is true when the file is not readable (or does not exist).usage >&2redirects the whole output of theusagefunction to standard error.exit 2andexit 1end the script with different statuses, so a caller can tell the two problems apart.wc -l < "$1"counts lines. Redirecting the file intowcmakes it print only the number, without the file name.
Adding Color
Terminals understand special character sequences, called ANSI escape codes, that change the text color. The sequence \033[32m switches to green, \033[31m to red, and \033[0m resets the color. In Bash, the $'...' form of quoting turns \033 into the real escape character.
green=$'\033[32m'
red=$'\033[31m'
reset=$'\033[0m'
printf '%sOK%s: backup finished\n' "$green" "$reset"
printf '%sFAIL%s: disk full\n' "$red" "$reset"
On a terminal the word OK appears in green and FAIL in red. In a file or a pipe, however, those escape characters would show up as unreadable clutter. The test [ -t 1 ] is true only when standard output (descriptor 1) is a terminal, so the script can use colors only when it makes sense:
if [ -t 1 ]; then
green=$'\033[32m'; red=$'\033[31m'; reset=$'\033[0m'
else
green=''; red=''; reset=''
fi
printf '%sOK%s: backup finished\n' "$green" "$reset"
printf '%sFAIL%s: disk full\n' "$red" "$reset"
When the script's output is piped into another command, the three variables are empty, and the plain text arrives without any escape codes:
OK: backup finished
FAIL: disk full
Updating a Line in Place
A carriage return (\r) moves the cursor back to the start of the current line without starting a new one. Printing a new message after it overwrites the old one, which is a simple way to show progress:
for i in 1 2 3; do
printf '\rProcessing %d/3' "$i"
done
printf '\n'
On a terminal, the line Processing 1/3 is replaced in place by Processing 2/3 and then Processing 3/3, and the final printf '\n' moves to the next line. Because the effect depends on a terminal, it is best used for messages meant for people at a keyboard, not for scripts whose output goes to log files.