update attempt to clarify more, using an example, does the following shell commands:

2nd line,
3rd line,
printf '%s' "$SHELLVARIABLE"

generate this output:

1st line,<newline>2nd line,<newline>3rd line,<newline>

<newline> being the character 0x0a / \n?

Original question formulation

What is the correct (POSIX-confirm) way to store a newline character 0x0a (aka known by its commen c style escap \n) into a shell variable.

I want to make sure that doing the following:


is, not merely working by chance but instead is indeed the correct way.

Since POSIX's printf is perfectly capable of producing a newline character (i.e. printf '\n', or printf '%b' '\0012') I first attempted a more explicit (? or correct?) form:

SHELLVARIABLE="$(printf '\n')"

though a tempting approach, does not work. As the according to the standard, command substitution (i.e. via $() and ` `) shall remove

sequences of one or more newlines at the end of the substitution.

Note: Asking to store a single trailing newline into a shell variable is only to abstract the more general use case (i indeed seek answer to) that is how to store a string into POSIX shell variable which ends with the newline character.


1 Answer 1


Using a hard newline in a quoted string is fine.

Though personally, I'd avoid it if you just want the newline: I find it looks odd and there's a slight risk of accidentally hitting extra spaces at the end of the first line (so you'd get e.g. <space><newline>). But that's just me.

Command substitution indeed strips trailing newlines, but only those. The workaround is to make sure that the final character is something other than a newline and then strip that character off.

Both of these should give you a newline:


nl2="$(printf '\nx')"
  • I am happy to read your answer confirming that I can use indeed a "hard newline" (is that how it is referred, when occring verbatitm in a thring?). Also great to have the alternative more explicit, yet overly "boilerplate" solution. Thank you. I would like to accept your answer, do you happen to know where there is a document/ref/spec that defines your given options? Sep 8, 2018 at 15:18
  • This works well but IMHO it's utterly ugly in shell scripts...
    – lxvs
    Jul 26 at 3:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.