0

I want to append a multiline string while preserving whitespace to an existing variable.

final_str='$one'
tmp=$(cat << 'EOM'

$two
$three
EOM
)
final_str=${final_str}${tmp}
echo $final_str

Output:

$one $two $three

Expected output:

$one 
$two 
$three

How do I achieve this using nowdoc? Are there any simpler ways to do this?

subtleseeker
  • 4,415
  • 5
  • 29
  • 41
  • `echo $final_str` itself loses your whitespace even if it was perfectly preserved up to that point. Always, _always_ quote your expansions (as http://shellcheck.net/ instructs). – Charles Duffy Jan 08 '22 at 17:03
  • BTW, `final_str+="$tmp"` is somewhat faster to run. – Charles Duffy Jan 08 '22 at 17:04
  • ...anyhow, see https://ideone.com/D7t2yK demonstrating that the failure to quote the expansion on the `echo` command really is the entirety of the issue at hand. – Charles Duffy Jan 08 '22 at 17:06
  • "Are there any simpler ways to do this?" Yes by using an array. What exactly is your goal? – konsolebox Jan 08 '22 at 17:06

0 Answers0