Building Help Messages with --help
A help message is the text a script prints when the user runs it with --help (or -h). It answers the questions a user has before running a command for real: what does it do, which arguments does it take, which options exist, what are their defaults, and what does a typical call look like. Almost every command-line tool on Linux follows the same conventions for this text, so a script that follows them feels familiar immediately: ls --help, grep --help and tar --help all start with a Usage: line, list their options in two aligned columns, print to standard output and exit with status 0.
This lesson builds on the usage and bad_usage functions used in lessons 125 to 130. It shows how to structure the text, where it must go, how to wire --help into both kinds of parsing loop, and how to keep the help short enough to read and accurate enough to trust.
What a Help Message Contains
A complete help message usually has these parts, in this order:
- The usage line, a compact summary of the command's syntax:
Usage: wordfreq.sh [OPTION]... [FILE]... - A one- or two-line description of what the command does.
- The options, one per line, with the short and long form on the left and a description on the right. Defaults are stated in the description.
- Examples of typical calls. Many users read these first.
- Exit status values, when the script uses more than 0 and 1.
Short scripts need only the first three parts. Longer ones can also list environment variables they read or files they use.
The Usage Line and Its Notation
The usage line uses a small notation that most command-line documentation shares:
| Notation | Meaning | Example |
|---|---|---|
[ ] | the part is optional | [-v] |
... | the part can be repeated | FILE... |
| UPPERCASE word | a placeholder the user replaces with a real value | -o FILE |
| | choose one of the alternatives | --color=auto|always|never |
| plain text | typed literally | -o, --help |
So Usage: rotate.sh [-k KEEP] [-z] FILE... says: -k is optional and takes a value called KEEP, -z is optional, and at least one FILE is required. [FILE]... means zero or more files, and [OPTION]... is a common short form when a script has too many options to list on one line.
When a script has several distinct ways of being called, it can print several usage lines:
Usage: notes.sh add TEXT
notes.sh list [-n NUM]
notes.sh delete ID
Where Help Goes: Standard Output and Exit Status 0
When the user asks for help, the help is the output of the command, so it goes to standard output and the script exits with status 0. That is what makes these work:
wordfreq.sh --help | less # page through long help
wordfreq.sh --help | grep -- -m # find one option
wordfreq.sh --help > help.txt # save it
An error is different. When the user made a mistake, the script prints a short message to standard error and exits with status 2, the usual status for wrong usage (lesson 116). Printing the whole help text on every typo buries the actual error message, so most tools print one line about the problem and one line pointing to --help:
wordfreq.sh: unknown option '-x'
Try 'wordfreq.sh --help' for more information.
The two cases side by side, using the complete example from the end of this lesson:
bash wordfreq.sh --help > /dev/null; echo "status $?"
bash wordfreq.sh -x notes.txt 2> /dev/null; echo "status $?"
status 0
status 2
The first command printed nothing on the terminal because all of the help went to standard output, which was discarded. The second printed nothing because both error lines went to standard error, which was discarded. A script that mixes these up (help on standard error, or errors on standard output) breaks pipes and log files in surprising ways.
Writing the Help Text with a Here Document
A here document (lesson 63) is the easiest way to write multi-line help, because the text appears in the script exactly as it will be printed:
prog=${0##*/}
usage() {
cat <<USAGE
Usage: $prog [OPTION]... [FILE]...
Print the most frequent words in each FILE, or in standard input
when no FILE is given or FILE is -.
Options:
-n, --top NUM show the NUM most frequent words (default: 10)
-i, --ignore-case count "The" and "the" as the same word
-h, --help show this help and exit
USAGE
}
The important details:
prog=${0##*/}removes the directory part of$0(lesson 54), so the help showswordfreq.shwhether the script was run as./wordfreq.sh,bash wordfreq.shor/usr/local/bin/wordfreq.sh. Using the real name means the help stays correct if the script is renamed.- The delimiter
USAGEis unquoted, so$progis expanded. Every other$, backquote and backslash in the text is also special. If the help needs a literal dollar sign, write\$, or quote the delimiter (<<'USAGE') and give up the expansion. - The closing
USAGEmust start at the beginning of its line. The help text itself is not indented, because every space in the body is printed. - Wrapping the text in a function lets the script print it from several places (
-h,--help, or ahelpsubcommand) without repeating it.
Handling --help in the Parsing Loop
With a manual while/case loop (lesson 127), --help is one more branch. It prints the help and exits immediately:
while (( $# > 0 )); do
case $1 in
-h|--help) usage; exit 0 ;;
--version) printf '%s %s\n' "$prog" "$version"; exit 0 ;;
-n|--top) (( $# > 1 )) || bad_usage "option '$1' requires an argument"
top=$2; shift ;;
--) shift; files+=("$@"); break ;;
-?*) bad_usage "unknown option '$1'" ;;
*) files+=("$1") ;;
esac
shift
done
# validation of values and required arguments comes after the loop
Two properties of this layout matter:
Help wins over missing or invalid arguments. Because validation happens after the loop, --help works even when the rest of the command line is incomplete. A user who types wordfreq.sh notes.txt --help gets the help, not an error about something else:
$ bash wordfreq.sh notes.txt --help
Usage: wordfreq.sh [OPTION]... [FILE]...
Print the most frequent words in each FILE, or in standard input
...
(The rest of the help is printed in full; it is shortened here.) If the script checked "at least one file is required" before parsing, wordfreq.sh --help with no files would fail, which is exactly the situation where the user most needs help.
-- turns --help into an ordinary argument. After --, nothing is treated as an option, so a file really named --help can still be processed:
$ bash wordfreq.sh -- --help
wordfreq.sh: --help: cannot read file
The script tried to open a file called --help, which does not exist in this folder, and exited with status 1.
A --version option is common next to --help. It prints the script name and version on one line to standard output and exits with status 0:
$ bash wordfreq.sh --version
wordfreq.sh 1.2.0
Short Usage When Required Arguments Are Missing
Some scripts print a short usage reminder when they are run with no arguments at all. Because this is still an error (the user did not ask for help), it goes to standard error with status 2:
prog=${0##*/}
if (( $# == 0 )); then
printf 'Usage: %s [OPTION]... FILE...\n' "$prog" >&2
printf "Try '%s --help' for more information.\n" "$prog" >&2
exit 2
fi
$ bash noargs.sh
Usage: noargs.sh [OPTION]... FILE...
Try 'noargs.sh --help' for more information.
Scripts whose operands are optional (like wordfreq.sh, which reads standard input when no file is given) must not do this, because running them without arguments is a valid call.
Adding --help to a getopts Script
getopts (lesson 130) understands only single-letter options, so --help normally ends up as the error illegal option -- -. A widely used workaround puts -: in the option string. getopts then treats - as an option that takes a value, so --help arrives as the option - with OPTARG set to help:
#!/usr/bin/env bash
prog=${0##*/}
usage() { printf 'Usage: %s [-v] [-o FILE] [--help] FILE...\n' "$prog"; }
verbose=0 output=
while getopts ":vo:h-:" opt; do
case $opt in
v) verbose=1 ;;
o) output=$OPTARG ;;
h) usage; exit 0 ;;
-) case $OPTARG in
help) usage; exit 0 ;;
*) printf "%s: unknown option '--%s'\n" "$prog" "$OPTARG" >&2; exit 2 ;;
esac ;;
:) printf "%s: option '-%s' requires an argument\n" "$prog" "$OPTARG" >&2; exit 2 ;;
\?) printf "%s: unknown option '-%s'\n" "$prog" "$OPTARG" >&2; exit 2 ;;
esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose output=[$output] files: $*"
$ bash gh.sh --help
Usage: gh.sh [-v] [-o FILE] [--help] FILE...
$ bash gh.sh -v -o out.txt a b
verbose=1 output=[out.txt] files: a b
$ bash gh.sh --verbose
gh.sh: unknown option '--verbose'
$ bash gh.sh --help=yes
gh.sh: unknown option '--help=yes'
$ bash gh.sh -- --help
verbose=0 output=[] files: --help
The inner case receives everything after the two dashes, which is why --help=yes arrives as help=yes and is rejected. -- still ends option parsing, because getopts recognizes it before looking at the option string. The same script gave the same --help result when run with Dash, but POSIX does not define what - in an option string means, so treat this as a convenience for --help and perhaps one or two other long options. A script that needs many long options is clearer with the manual loop.
Keeping the Help in Header Comments
Another style keeps the help text in specially marked comments at the top of the script and prints them with sed. The documentation and the code then live in one place, and anyone who opens the file sees the help first:
#!/usr/bin/env bash
## Usage: doc.sh [-h] NAME
## Print a greeting for NAME.
##
## -h show this help and exit
# (a normal comment, not part of the help)
usage() { sed -n 's/^## \{0,1\}//p' "$0"; }
[[ ${1-} == -h ]] && { usage; exit 0; }
echo "Hello, ${1:?missing NAME}"
$ bash doc.sh -h
Usage: doc.sh [-h] NAME
Print a greeting for NAME.
-h show this help and exit
sed -n prints nothing by default; the s command with the p flag prints only the lines where ## (or a bare ##) was found at the start and removed. Normal # comments are skipped. The limitation is that the text cannot use variables: the script name is written literally, so it goes out of date if the file is renamed, and the default values in the text are not tied to the variables in the code. This style also depends on $0 being the path of the script file, which is true when the script is run directly or with bash file, but not when it is sourced.
Formatting the Option List
A few layout habits make help text easy to scan:
- Align the descriptions in one column. Put the short form first, then the long form; when an option has no short form, indent its long form so the long forms line up (
--version). - Write the value placeholder once, after the long form (
-n, --top NUM), and use the same placeholder name in the description ("show the NUM most frequent words"). - State defaults in the description:
(default: 10). - Keep lines under 80 characters. Terminals are often 80 columns wide, and long lines wrap in the middle of words. This is easy to check:
bash wordfreq.sh --help | awk '{ if (length($0) > m) m = length($0) } END { print NR, "lines, widest", m }'
20 lines, widest 75
- Describe what the option does, not how it is implemented. "ignore words shorter than LEN letters" is better than "filter with awk length".
A Complete Example
wordfreq.sh prints the most frequent words in text files. Its help text follows every convention in this lesson, and its errors use the short two-line form.
#!/usr/bin/env bash
# wordfreq.sh - print the most frequent words in text files
set -euo pipefail
prog=${0##*/}
version=1.2.0
usage() {
cat <<USAGE
Usage: $prog [OPTION]... [FILE]...
Print the most frequent words in each FILE, or in standard input
when no FILE is given or FILE is -.
Options:
-n, --top NUM show the NUM most frequent words (default: 10)
-i, --ignore-case count "The" and "the" as the same word
-m, --min-length LEN ignore words shorter than LEN letters (default: 1)
-h, --help show this help and exit
--version show version information and exit
Examples:
$prog -n 5 notes.txt five most frequent words in notes.txt
$prog -i -m 4 *.md ignore case and words under 4 letters
cat log.txt | $prog read from standard input
Exit status:
0 success
1 a FILE could not be read
2 invalid command-line usage
USAGE
}
bad_usage() {
printf '%s: %s\n' "$prog" "$*" >&2
printf "Try '%s --help' for more information.\n" "$prog" >&2
exit 2
}
top=10 ignore_case=0 min_len=1
files=()
while (( $# > 0 )); do
case $1 in
-h|--help) usage; exit 0 ;;
--version) printf '%s %s\n' "$prog" "$version"; exit 0 ;;
-n|--top) (( $# > 1 )) || bad_usage "option '$1' requires an argument"
top=$2; shift ;;
--top=*) top=${1#*=} ;;
-i|--ignore-case) ignore_case=1 ;;
-m|--min-length) (( $# > 1 )) || bad_usage "option '$1' requires an argument"
min_len=$2; shift ;;
--min-length=*) min_len=${1#*=} ;;
--) shift; files+=("$@"); break ;;
-?*) bad_usage "unknown option '$1'" ;;
*) files+=("$1") ;;
esac
shift
done
[[ $top =~ ^[1-9][0-9]{0,3}$ ]] || bad_usage "NUM must be a number from 1 to 9999, got '$top'"
[[ $min_len =~ ^[1-9][0-9]?$ ]] || bad_usage "LEN must be a number from 1 to 99, got '$min_len'"
(( ${#files[@]} > 0 )) || files=(-)
status=0
for f in "${files[@]}"; do
if [[ $f != - && ! -r $f ]]; then
printf '%s: %s: cannot read file\n' "$prog" "$f" >&2
status=1
continue
fi
(( ${#files[@]} > 1 )) && printf '==> %s <==\n' "$f"
cat -- "$f" |
tr -cs '[:alpha:]' '\n' |
{ if (( ignore_case )); then tr '[:upper:]' '[:lower:]'; else cat; fi; } |
awk -v min="$min_len" 'length($0) >= min' |
sort | uniq -c | sort -k1,1nr -k2,2 | head -n "$top"
done
exit "$status"
How It Works
usageprints the full help to standard output. It is called only for-hand--help, both of which exit with status 0.bad_usageprints one line describing the problem and theTry '... --help'hint, both to standard error, and exits with status 2. Every usage error in the script goes through it, so all messages have the same format.- The parsing loop only records choices.
--helpis handled as soon as it is seen, before any validation. - Validation after the loop checks the two numbers with regular expressions (lesson 128). The error messages use the same placeholder names as the help text (NUM, LEN), so the user can find the matching line in the help.
- No file means standard input.
files=(-)makes the loop read-, andcat -- -reads standard input. That is why the usage line shows[FILE]...and why the script does not complain when run without arguments. - The counting pipeline splits the text into one word per line (
tr -cs '[:alpha:]' '\n'turns every run of non-letters into a newline), optionally lowercases it, drops short words withawk, and counts withsort | uniq -c(lesson 107). The finalsort -k1,1nr -k2,2sorts by count, highest first, and alphabetically within the same count.
Running the Complete Example
The file notes.txt contains two lines:
The cat and the dog. The end.
A cat is not a dog, and the dog knows it.
$ bash wordfreq.sh -n 3 notes.txt
3 dog
2 The
2 and
$ bash wordfreq.sh -i -n 4 -m 3 notes.txt
4 the
3 dog
2 and
2 cat
In the first run, The and the are counted separately; The sorts before and because the sandbox used the C locale, where capital letters come before lowercase ones. With -i, the two spellings merge into a count of 4, and -m 3 removes the one- and two-letter words.
Reading from standard input and processing two files:
$ printf 'b a b\n' | bash wordfreq.sh
2 b
1 a
$ bash wordfreq.sh -n 2 notes.txt notes.txt
==> notes.txt <==
3 dog
2 The
==> notes.txt <==
3 dog
2 The
The help, the version and the error messages:
$ bash wordfreq.sh --help
Usage: wordfreq.sh [OPTION]... [FILE]...
Print the most frequent words in each FILE, or in standard input
when no FILE is given or FILE is -.
Options:
-n, --top NUM show the NUM most frequent words (default: 10)
-i, --ignore-case count "The" and "the" as the same word
-m, --min-length LEN ignore words shorter than LEN letters (default: 1)
-h, --help show this help and exit
--version show version information and exit
Examples:
wordfreq.sh -n 5 notes.txt five most frequent words in notes.txt
wordfreq.sh -i -m 4 *.md ignore case and words under 4 letters
cat log.txt | wordfreq.sh read from standard input
Exit status:
0 success
1 a FILE could not be read
2 invalid command-line usage
$ bash wordfreq.sh --version
wordfreq.sh 1.2.0
$ bash wordfreq.sh -x notes.txt
wordfreq.sh: unknown option '-x'
Try 'wordfreq.sh --help' for more information.
$ bash wordfreq.sh -n
wordfreq.sh: option '-n' requires an argument
Try 'wordfreq.sh --help' for more information.
$ bash wordfreq.sh -n abc notes.txt
wordfreq.sh: NUM must be a number from 1 to 9999, got 'abc'
Try 'wordfreq.sh --help' for more information.
$ bash wordfreq.sh missing.txt
wordfreq.sh: missing.txt: cannot read file
The help and version runs exit with status 0, the three usage errors with status 2, and the unreadable file with status 1, exactly as the "Exit status" section of the help promises. The default values shown in the help (10 and 1) are written as plain text here; lesson 132 shows how to print them from the same variables the script uses, so the help can never disagree with the code. Lesson 133 looks more closely at the error side: suggesting the right option when the user makes a typo, and reporting several problems at once.