To print a newline in Bash, you have several methods depending on your use case. Below are the most common and reliable approaches:
1. Using echo
with -e
(Interpret Escape Sequences)
echo -e "First line\nSecond line"
Output:
First line
Second line
Note:
- The
-e
flag enables interpretation of escape characters like\n
. - Behavior of
echo
can vary between shells. Useprintf
for more consistency (see below).
2. Using printf
(Recommended for Portability)
printf "First line\nSecond line\n"
Output:
First line
Second line
Advantages:
printf
handles escape sequences by default (no flags needed).- More consistent across shells/OSes compared to
echo
. - Add
\n
at the end to avoid trailing%
symbols in some shells.
3. Using ANSI-C Quoting ($'...'
Syntax)
echo $'First line\nSecond line'
Output:
First line
Second line
Note:
- The
$'...'
syntax interprets escape sequences automatically (no-e
required). - Works in Bash, Zsh, and other modern shells.
4. Store Newline in a Variable
newline=$'\n'
echo "Hello${newline}World"
Output:
Hello
World
Key Differences Between echo
and printf
Method | Escape Handling | Portability | Auto Newline? |
---|---|---|---|
echo -e | Requires -e flag | Varies between shells | Yes (by default) |
printf | Default | Highly portable | No (add \n explicitly) |
$'...' | No flags needed | Bash/Zsh only | Depends on command |
Examples in Context
Multi-line String
printf "Line 1\nLine 2\nLine 3\n"
Combine Variables with Newlines
name="Alice"
message="Hello, $name!\nWelcome to Bash."
printf "$message\n"
Write to a File
printf "First line\nSecond line\n" > output.txt
Troubleshooting
- If your
echo
command prints\n
literally, use-e
or switch toprintf
. - For scripts targeting POSIX compliance, use
printf
to avoid shell-specific quirks. - Avoid
echo -e
if your script needs to run in shells where-e
is unsupported (e.g., older/dash-based systems).
Summary
- Best Practice: Use
printf
for cross-shell compatibility. - Quick Fix:
echo -e
or$'...'
syntax for simple cases. - Avoid:
echo "text\n"
without-e
or$'...'
, as it will print\n
literally.