Using echo and printf

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 30 of 205

Scripts need to talk: they print messages, results and error text. Bash has two built-in commands for this, echo and printf. The echo command is quick and simple. The printf command is more precise: it can align columns, pad numbers, format decimals and print the same text on every system. This lesson explains both, shows where echo surprises people, and helps you decide which to use.

Understanding the Concept

Both commands write text to standard output, the stream that normally appears in your terminal, and both are Bash built-ins. You can confirm that:

type echo printf
echo is a shell builtin
printf is a shell builtin

The difference is how they treat their arguments:

  • echo prints its arguments separated by single spaces, then adds a newline. It has a few options, and its handling of backslash sequences varies between shells.
  • printf takes a format string first and then values. The format controls the layout, the way the printf function does in C. It prints exactly what the format says, and it adds a newline only if the format contains one.

The echo Command

The simplest use prints the words you give it:

echo Hello, Bash
Hello, Bash

Quoting and Spaces

Bash splits an unquoted command line into words, and echo prints those words with one space between them. Extra spaces are lost:

echo "Hello,   Bash"
echo Hello,     Bash
Hello,   Bash
Hello, Bash

In the first line the quotes make one argument, so the three spaces stay. In the second line, echo received two separate arguments, Hello, and Bash. The same effect applies to variables, which is why variables should usually be in double quotes:

msg="  spaced   text  "
echo $msg
echo "$msg"
spaced text
  spaced   text  

Quotes and Special Characters

Inside single quotes nothing is replaced. Inside double quotes variables and commands are replaced:

echo 'single $HOME'
echo "double $HOME"
single $HOME
double /home/suriya

An unquoted * is expanded by Bash into the names of the files in the directory, before echo sees it:

echo *
echo "*"

With two files named one.txt and two.txt present:

one.txt two.txt
*

Printing a Blank Line

echo with no arguments prints an empty line:

echo "before"
echo
echo "after"
before

after

The -n Option: No Newline

By default, echo ends its output with a newline. The -n option suppresses it, so the next output continues on the same line:

echo -n "no newline"
echo "<- same line"
no newline<- same line

This is useful for prompts, where the cursor should stay right after the text.

The -e Option: Backslash Escapes

By default, Bash's echo prints backslashes literally. With -e, it interprets escape sequences:

echo "Line1\nLine2"
echo -e "Line1\nLine2"
Line1\nLine2
Line1
Line2

The common sequences are:

SequenceMeaning
\nNew line
\tTab
0A single backslash
\bBackspace
\cStop printing here, and do not print the newline
\xHHThe character with the hexadecimal code HH
\0NNNThe character with the octal code NNN (a leading zero is required)

Examples:

echo -e "Col1\tCol2"
echo -e "back\\\\slash"
echo -e "keep\c going"
echo -e '\x41'
Col1	Col2
back\slash
keep
A

The -E option turns escape processing off again, which is the default:

echo -E "a\tb"
a\tb

In Bash, you can also write special characters with the $'...' quoting form, which is processed by the shell and works without any option:

echo $'tab\there'
tab	here

You may combine options: echo -ne "x\ty\n" is the same as echo -n -e "x\ty\n".

When echo Is Unreliable

echo has two weaknesses that matter when a script must behave the same everywhere.

1. An argument that looks like an option is taken as one. If the text starts with -n, -e or -E, echo treats it as an option and prints nothing for it:

echo "-n"
echo -- "-n"
-- -n

The first command printed nothing at all. The second printed -- -n because Bash's echo does not recognize -- as the end of the options. When the text to print comes from a variable or user input, echo is not safe, and printf '%s\n' "$text" always works.

2. Shells differ in how they handle backslashes. In Bash, echo "a\tb" prints the backslash. In Dash, the sh of Debian and Ubuntu, the same command prints a tab, and echo -e prints a stray -e:

sh -c 'echo "a\tb"'
sh -c 'echo -e "x\ty"'
a	b
-e x	y

Bash also has an option called xpg_echo (off by default) that makes its echo behave like this. Because of such differences, printf is the portable choice.

The Exit Status

echo returns status 0 when it works:

echo hi > /dev/null
echo "status=$?"
status=0

The printf Command

The printf command takes a format string and then values:

printf format [arguments...]

The simplest use prints fixed text. Unlike echo, it does not add a newline, so you write \n yourself:

printf "Hello, Bash\n"
printf "Hello, Bash"
echo "<-"
Hello, Bash
Hello, Bash<-

Inside the format, backslash sequences such as \n and \t are always processed:

printf "Tab:\tEnd\n"
Tab:	End

Format Specifiers

A format specifier begins with % and marks where a value goes. The most useful ones are:

SpecifierPrints
%sA string
%dA whole number (decimal integer)
%fA number with a decimal point
%x, %XA whole number in hexadecimal (lowercase, uppercase)
%oA whole number in octal
%eA number in scientific notation
%cThe first character of the argument
%bA string, with backslash escapes processed
%qA string, quoted so that the shell can read it back
%%A literal percent sign
printf "%s is %d years old\n" Asha 30
Asha is 30 years old

The format has two specifiers, %s and %d, and printf fills them with Asha and 30 in order. Other examples:

printf "%x %X %o\n" 255 255 8
printf "%f\n" 3.14159
printf "%e\n" 12345.678
printf "%c\n" Hello
printf "100%%\n"
ff FF 10
3.141590
1.234568e+04
H
100%

Numbers may be given in other bases. A leading 0x means hexadecimal and a leading 0 means octal:

printf "%d\n" 42 "0x1F" 010
42
31
8

Width, Precision and Flags

A specifier can include numbers that control the layout:

%[flags][width][.precision]specifier
  • width is the minimum number of characters. Shorter values are padded.
  • precision is the number of digits after the decimal point for %f, or the maximum number of characters for %s.
  • flags: - aligns the text to the left, 0 pads numbers with zeros, and + always shows a sign.
printf "%5d|\n" 42
printf "%-5d|\n" 42
printf "%05d|\n" 42
printf "%+d\n" 42
printf "%.2f\n" 3.14159
printf "%8.2f|\n" 3.14159
printf "%10s|\n" abc
printf "%-10s|\n" abc
printf "%.3s\n" abcdefgh
   42|
42   |
00042|
+42
3.14
    3.14|
       abc|
abc       |
abc

The vertical bar after each value shows where the field ends, so you can see the padding.

Reusing the Format

If there are more arguments than specifiers, printf repeats the whole format until every argument is used. This makes loops unnecessary for printing lists:

printf "%s\n" one two three
printf "%s=%s\n" a 1 b 2 c
one
two
three
a=1
b=2
c=

In the second example the last c has no partner, so the second %s prints as empty. Missing values are treated as an empty string for %s and as 0 for %d:

printf "%d\n"
printf "%s|%s|\n" onlyone
0
onlyone||

Invalid Numbers

If %d receives something that is not a number, printf reports an error, prints 0 (or the leading digits), and returns status 1:

printf "%d\n" abc
echo "status=$?"
printf "%d\n" 3.7
echo "status=$?"
bash: printf: abc: invalid number
0
status=1
bash: printf: 3.7: invalid number
3
status=1

Use %f for numbers with a decimal point.

%b and %q

The %b specifier processes backslash escapes in a value, unlike %s, which prints a value as it is:

printf '%b\n' 'a\tb\nc'
printf '%s\n' 'a\tb'
a	b
c
a\tb

The %q specifier turns a value into a form that is safe to paste back into a shell:

printf "%q\n" "hello world; rm -rf *"
hello\ world\;\ rm\ -rf\ \*

Printing Safely

Never place unknown text in the format position, because any % or backslash in it would be interpreted. Put the text in a value instead:

printf '%s\n' "$text"

This also fixes the -n problem from before:

printf "%s\n" "-n"
-n

Storing the Result with printf -v

The -v option stores the formatted text in a variable instead of printing it:

printf -v padded "%03d" 7
echo "$padded"
007

The format %03d pads the number 7 with zeros to three characters. This avoids starting a separate process, as $(printf ...) would.

Printing Dates

Bash's printf has a %(format)T specifier for dates and times. The argument is a number of seconds since 1970, and the special value -1 means "now":

printf '%(%Y)T\n' 0
1970

A common use is a timestamp for a log message:

printf '%(%Y-%m-%d %H:%M:%S)T %s\n' -1 "backup started"

The output has the current date and time, in a form such as 2026-11-20 14:03:09 backup started. The %(...)T form needs Bash 4.2 or later. (The time-format letters inside the parentheses are those of the date command and the C strftime function.)

Printing Arrays

Because printf repeats its format, it prints every element of an array on its own line with one command:

files=(a.txt "b c.txt" d.txt)
printf '%s\n' "${files[@]}"
a.txt
b c.txt
d.txt

The expression "${files[@]}" expands to each element as a separate word, so the element with a space stays together. Compare with echo, which would join them all on one line:

echo "${files[@]}"
a.txt b c.txt d.txt

Building a Table

Width and precision make aligned columns easy:

printf "%-10s %6s\n" Item Price
printf "%-10s %6.2f\n" Pen 1.5 Notebook 12.25
Item        Price
Pen          1.50
Notebook    12.25

The first line uses %-10s (a left-aligned text column of width 10) and %6s (a right-aligned column of width 6). The second line formats the prices with two decimals. Because there are four values and the format has two specifiers, the format is applied twice, so each row is printed in the same layout.

Writing to Standard Error

Error messages should go to standard error, so they are not mixed with normal output when the output is redirected. Add >&2 to send the output there:

echo "error text" >&2
printf "error text\n" >&2

Both print the message in the terminal, but when you run the script with ./script.sh > out.txt, the message still appears on the screen and does not end up in the file. A later lesson on redirection explains the streams in detail.

Terminal Colors

Escape sequences that begin with the escape character \033 change the style of terminal text. This prints the word Bold in bold, and then resets the style:

printf '\033[1mBold\033[0m\n'

The \033[1m part switches bold on, and \033[0m switches all styles off. The output looks like Bold on a terminal that supports it. If output is written to a file, the escape characters are saved too, so print colors only when the output goes to a terminal.

Choosing Between echo and printf

TaskUse
A short fixed messageecho "Done"
A prompt that stays on the same lineprintf "Name: " or echo -n
Text that might start with - or hold backslashesprintf '%s\n' "$text"
Numbers with padding, decimals or alignmentprintf
Several values in a tableprintf
A script that must work in sh as well as Bashprintf

In practice, echo is fine for simple messages with text that you control, and printf is the better choice whenever the text comes from a variable, a file or a user.

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 Using echo and printf and get answers drawn from it.

Signed-in readers only.