0

How can I add a new line character (\n) between two Unix variables?

I tried the following but it's getting printed in a single line instead of separate lines.

h=hello
w=world
c="$h"$'\n'"$w"
echo $c
Output: hello world
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

1

Your solution works but you must quote $c in your echo statement for it to expand the way you want.

Like this:

h=hello
w=world
c="$h"$'\n'"$w"
echo "$c"

However this is almost certainly an x-y problem. What do you ultimately need to accomplish?

As is it would be much better to just do:

h=hello
w=world
printf '%s\n' "$h" "$w"

Alternatively you can use the -e option to echo:

h=hello
w=world
c="${h}\n${w}"
echo -e "$c"
jesse_b
  • 37,005