How do I read multiple lines from STDIN into a variable?

man bash mentions «…

The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

…»

$ myVar=$(</dev/stdin)
hello
this is test
$ echo $myVar
hello this is test
$ echo "$myVar"
hello
this is test

and I agree this is worth mentioning — echo "$myVar" would have displayed the input as it was given.


Try this:

user@host:~$ read -d '' x <<EOF
> mic
> check
> one
> two
> EOF

Without line breaks:

user@host:~$ echo $x
mic check one two

With line breaks:

user@host:~$ echo "$x"
mic
check
one
two

Refer to the excellent Bash Guide for all your bash scripting needs.

In particular the Bash FAQ contains this at number #1:

How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?


I've solved this issue by dealing with each line until I came up with a blank line. It works well enough for my situation. But if someone wants to add a better solution, feel free to do so.

echo "---
notes: |" > 'version.yml'

while read line
do
  # break if the line is empty
  [ -z "$line" ] && break
  echo "  $line" >> "source/application.yml"
done