Newlines in shell variables

Hello,

I'm trying to create a shell variable with newlines inside it, so that when I echo the variable and pipe it to, say, awk, it output with the newlines. Why is this so problematic? I frankly don't know, but BASH seems to be stripping my variable of newlines. Here's an example

$ cat script.sh
#!/bin/bash

list="hello " # first hello
list=$list`echo ""` # should then put a newline after hello
list=$list'

' # This should too
list=$list"world" # and world on the next row

echo $list # now see what happens...
$ ./script.sh
hello world

WHY DOES IT TAKE AWAY MY NEWLINES? I solved it by creating a temporary file, output everything there, and then read from the file, but I don't want to do that!

Does anyone know how to store newlines in a shell varabile? Thanks a bunch,

Marcus

bash gives alot of help here. From the bash man page:

     echo [-neE] [arg ...]
          Output the args, separated by  spaces,  followed  by  a
          newline.   The  return  status  is  always 0.  If -n is
          specified, the trailing newline is suppressed.  If  the
          -e  option  is  given,  interpretation of the following
          backslash-escaped characters is enabled.  The -E option
          disables the interpretation of these escape characters,
          even on systems where they are interpreted by  default.
          echo  does not interpret -- to mean the end of options.
          echo interprets the following escape sequences:
          \a   alert (bell)
          \b   backspace
          \c   suppress trailing newline
          \e   an escape character
          \f   form feed
          \n   new line
          \r   carriage return
          \t   horizontal tab
          \v   vertical tab
          \\   backslash
          \nnn the character whose ASCII code is the octal  value
               nnn (one to three digits)
          \xnnn
               the character whose ASCII code is the  hexadecimal
               value nnn (one to three digits)

By the way, your specific issue is that you do not have quotes around your variable:

echo "$list" # now see what happens...
1 Like

Thanks tmarikle, but that unfortunatly doesn't do it.

$ cat script.sh
#!/bin/bash

list="hello " # first hello
list=$list`echo -e "\ntest\n "` # As per advice from tmarikle
list=$list"world" # and world on the next row

echo $list # now see what happens...
$ ./script.sh
hello test world
$

I think it has something to do with bash variables, being stripped of newlines. It is SO frustrating!

Ah!

Hah, silly me. Yes, of course. Thanks a bunch,

echo "$list"

works just fine.

Marcus

This thread saved my life :slight_smile:

You guys rock!

--
Pavan.