How to add newlines into variables in bash script
When I do
I get the
\nprinted out too. How can I have newlines then?
While the answers here are great, in reality I think you'd be better off using an array for this sort of thing most of the time.
bashyou can use the syntax
Single quotes preceded by a
$is a new syntax that allows to insert escape sequences in strings.
printfbuiltin 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:
because when you print the string without quotes, newline are converted to spaces.
What is the syntax `str=$'Hello World\n===========\n'` called? variable substitution?
@zengr: It's called ANSI-C quoting, and it's also supported in `zsh` and `ksh`; however, it is NOT POSIX-compliant.
@mkelement0, it comes from ksh93, is also supported by zsh, bash, mksh and FreeBSD sh, and its inclusion in the next major revision of POSIX is under discussion