Variables

Embedded newlines

You have a script:

$ cat myscript
abc
def
ghi
$

Now you do

$ declare RESULT=$(myscript)
myscript: line 1: abc: command not found
myscript: line 2: def: command not found
myscript: line 3: ghi: command not found
$

The shell tries to execute the lines as commands. So try this

$ declare RESULT=$(<myscript)
$ echo $RESULT
abc def ghi
$

the < avoids executing the command but the newlines have "disappeared"

$ echo "$RESULT"
abc
def
ghi
$

The difference is that

  1. The double-quoted version of the variable preserves internal spacing of the value exactly as it is represented in the variable, newlines, tabs, multiple blanks and all, whereas
  2. The unquoted version replaces each sequence of one or more blanks, tabs and newlines with a single space.

Thanks to stackoverflow.com

If you embed newlines in a variable this way, you get:

$ RESULT="abc\ndef\nghi"
$ echo $RESULT
abc\ndef\nghi
$ echo -e $RESULT
abc
def
ghi
$

In the "myscript" example, the variable actually contains the 0X0a newline character. In this example, the variable contains literally a backslash character and the letter n not a newline character. The -e option enable interpretation of the backslash escapes which include \n. The actual newlines don't appear until the variable is echoed.

To construct a variable containing real newlines, not just escape sequences:

$ NL='
> '
RESULT='abc'"$NL"'def'"$NL"'ghi'
$ echo "$RESULT"
abc
def
ghi
$

or

$ NL='
> '
RESULT="abc${NL}def${NL}ghi"
$ echo "$RESULT"
abc
def
ghi

The form ${var} is the general form for dereferencing a variable. It is generally optional but required if other alpha-numeric characters are juxtaposed with the variable name as they are here.


Send mail to the Webmaster

logo This site best viewed with a browser
Warning: This is a Debian centric site and MAY contain peanuts.
Many thanks to Debra Lynn and Ian Murdock for making Debian possible
First created Oct 16, 2011 ~ Last revised October 16, 2011

Valid XHTML 1.0 Strict Valid CSS!