Displaying Helpful Messages in Scripts

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 32 of 205

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 >&2 redirects the whole output of the usage function to standard error.
  • exit 2 and exit 1 end the script with different statuses, so a caller can tell the two problems apart.
  • wc -l < "$1" counts lines. Redirecting the file into wc makes 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.

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 Displaying Helpful Messages in Scripts and get answers drawn from it.

Signed-in readers only.