Building Help Messages with --help

Su Suriya Ravichandran Updated 06 Dec 2026
15 min read ·Lesson 131 of 205

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:

  1. The usage line, a compact summary of the command's syntax: Usage: wordfreq.sh [OPTION]... [FILE]...
  2. A one- or two-line description of what the command does.
  3. 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.
  4. Examples of typical calls. Many users read these first.
  5. 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:

NotationMeaningExample
[ ]the part is optional[-v]
...the part can be repeatedFILE...
UPPERCASE worda placeholder the user replaces with a real value-o FILE
|choose one of the alternatives--color=auto|always|never
plain texttyped 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 shows wordfreq.sh whether the script was run as ./wordfreq.sh, bash wordfreq.sh or /usr/local/bin/wordfreq.sh. Using the real name means the help stays correct if the script is renamed.
  • The delimiter USAGE is unquoted, so $prog is 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 USAGE must 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 a help subcommand) 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

  • usage prints the full help to standard output. It is called only for -h and --help, both of which exit with status 0.
  • bad_usage prints one line describing the problem and the Try '... --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. --help is 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 -, and cat -- - 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 with awk, and counts with sort | uniq -c (lesson 107). The final sort -k1,1nr -k2,2 sorts 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Building Help Messages with --help and get answers drawn from it.

Signed-in readers only.