PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

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

 September 05, 2022     bash, input, trim     No comments   

Issue

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"


Answered By - xhienne
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing