Here I'm trying to declare a variable with multi-line value in bash
:
$ GET="$(cat <<EOF
> GET / HTTP/1.1
> Host: 127.0.0.1:80
>
> EOF
> )"
That works for sure, however blank line at the end of the doc is lost:
$ echo "$GET"
GET / HTTP/1.1
Host: 127.0.0.1:80
$ cat <<< "$GET"
GET / HTTP/1.1
Host: 127.0.0.1:80
It's actually not the heredoc that trims the trailing newline, but the command substitution. Consider using read
instead:
$ IFS= read -r -d '' var << EOF
> hello
> world
>
> EOF
$ printf "%s" "$var"
hello
world
$
Note that printf
usually doesn't print a trailing newline, so the variable var
actually have two trailing newlines.
Alternative you can simply use multi line strings:
var=" hello
world
"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With