Echo newline in Bash prints literal \n - Stack Overflow #936
Labels
forum-discussion
Quotes clipped from forums
linux
Linux notes tools links
shell-script
shell scripting in Bash, ZSH, POSIX etc
Echo newline in Bash prints literal \n
Snippet
Full Content
Echo newline in Bash prints literal \n - Stack Overflow
How do I print a newline? This merely prints \n:
Answers
Use
printf
insteadprintf
behaves more consistently across different environments thanecho
.Make sure you are in Bash
The
-e
flag "enables interpretation of backslash escapes".Use
$'
quotingprints:
The
$'
strings use ANSI C Quoting.Use double quotes
This works both inside a script and from the command line. On the command line, press
Shift+Enter
to do the line break inside the string.Use a new parameter expansion in Bash 4.4
This expands the variable with backslash escape sequences.
Simply type
echo
to get a new line.
Use single quotes instead of double quotes
This also works, as the behavior of
echo
can vary across versions and distributions.Other approaches
There are a number of other techniques shown in the answers, such as using
sed
,jq
, or multipleecho
calls. However, the most reliable and portable solutions are usingprintf
or the$'
quoting mechanism.Suggested labels
None
The text was updated successfully, but these errors were encountered: