0

Why in this case doesnt generate new lines in Bash:

#!/bin/bash

function sample() {
    local DATA=""
    DATA="test1"$'\n'
    DATA="${DATA}test2"$'\n'
    echo ${DATA}
}


DATA=$(sample)
printf "%s" "${DATA}"
Macsurf
  • 17
  • 6

2 Answers2

0

$DATA is expanded, and all whitespace (including newlines) are used for word-splitting, before echo ever runs. You should always quote parameters expansions.

sample() {
    local DATA=""
    DATA="test1"$'\n'
    DATA="${DATA}test2"$'\n'
    echo "${DATA}"
}
chepner
  • 497,756
  • 71
  • 530
  • 681
-2

You must use the -e option of echo for it to interpret the \n character:

echo -e "${DATA}"
Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44