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
  • 66,199
  • 35
  • 114
  • 250
  • Related: [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/q/131766/237982) – jesse_b Jun 07 '19 at 19:14

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
  • 35,934
  • 12
  • 91
  • 140