How to add newlines into variables in bash script
In bash
you can use the syntax
str=$'Hello World\n===========\n'
Single quotes preceded by a $
is a new syntax that allows to insert escape sequences in strings.
Also printf
builtin allows to save the resulting output to a variable
printf -v str 'Hello World\n===========\n'
Both solutions do not require a subshell.
If in the following you need to print the string, you should use double quotes, like in the following example:
echo "$str"
because when you print the string without quotes, newline are converted to spaces.
You can put literal newlines within single quotes (in any Bourne/POSIX-style shell).
str='Hello World
===========
'
For a multiline string, here documents are often convenient. The string is fed as input to a command.
mycommand <<'EOF'
Hello World
===========
EOF
If you want to store the string in a variable, use the cat
command in a command substitution. The newline character(s) at the end of the string will be stripped by the command substitution. If you want to retain the final newlines, put a stopper at the end and strip it away afterward. In POSIX-compliant shells, you can write str=$(cat <<'EOF'); str=${str%a}
followed by the heredoc proper, but bash requires the heredoc to appear before the closing parenthesis.
str=$(cat <<'EOF'
Hello World
===========
a
EOF
); str=${str%a}
In ksh, bash and zsh, you can use the $'…'
quoted form to expand backslash escapes inside the quotes.
str=$'Hello World\n===========\n'
If you need newlines in your script many times you could declare a global variable holding a newline. That way you can use it in double-quoted strings (variable expansions).
NL=$'\n'
str="Hello World${NL} and here is a variable $PATH ===========${NL}"