Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heredoc not preserving blank line

Tags:

bash

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
like image 528
NarūnasK Avatar asked Jun 08 '16 15:06

NarūnasK


1 Answers

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
"
like image 70
Andreas Louv Avatar answered Nov 05 '22 03:11

Andreas Louv