Search code examples
bashinputtrim

How to preserve leading spaces whern reading from a here-document with read?


When using the following

read -r -d '' VAR <<EOF
  first line
  second line
EOF
echo "$VAR"

the leading spaces in the first line are trimmed:

first line
  second line

How can I echo the leading spaces in the first line and get the following?

  first line
  second line

Please note that this is a simplified example and that I need to use here document!


Solution

  • When your read into a variable you specify as a parameter, the leading and ending characters in IFS are considered delimiters and thus are removed.

    First solution: empty IFS temporarily

    IFS= read -r -d '' VAR <<EOF
      first line
      second line
    EOF
    printf '%s\n' "$VAR"
    

    Second solution (non-portable): don't specify a variable and Bash will use the default variable REPLY

    read -r -d '' <<EOF
      first line
      second line
    EOF
    printf '%s\n' "$REPLY"