Page 1 of 1

Bash, append \n to a string

Posted: Sun Aug 25, 2013 8:32 am
by honda4life
Hello,

I can't figure out how to add a \n to the end of a string.
The purpose is to build a very simple csv string.
I did some research on the net but it isn't clear. I've read some things with 'echo -e' but bash isn't that simple as python etc.

If the variable > 0 (has data), add a \n before adding new data.
Next step is to upload it to Xively buth without a new line it doesn't work.

Re: Bash, append \n to a string

Posted: Sun Aug 25, 2013 9:42 am
by redhawk
I'm not sure what you're doing wrong \n is working for me:
#!/bin/bash
string="Hello"
append="\ne\nl\nl\no"
string="$string""$append"
echo -e $string
Perhaps you could post some samples of your script code for checking.

Richard S.

Re: Bash, append \n to a string

Posted: Sun Aug 25, 2013 11:40 am
by honda4life
This is where it happens, echo is OK
Echo to the data variable is the solution?

Code: Select all

                if [ ${#data} -gt 0 ]; then
                        data="$data\n"
                fi
                data="$data$sensor,$temp"
        done

                echo -e $data
When looking at the data received at xively:
28-000004eef0d4,28.062\n28-000004eec74b,31.062

Maybe it's better to append a CrLf as octal value? But it's not that clean.

Re: Bash, append \n to a string

Posted: Sun Aug 25, 2013 11:55 am
by honda4life
if [ ${#data} -gt 0 ]; then
data="$data\n"
fi
data="$data$sensor,$temp"
done

echo -e $data
data=$(echo -e $data)
works :mrgreen:

Re: Bash, append \n to a string

Posted: Thu Sep 05, 2013 12:31 pm
by ukscone
you've already solved it so this is is moot but i always use the -n option when I use -e that way the newlines only occur when i want then too rather than if the echo implementation decides to put them in.

Code: Select all

pi@raspberrypi ~ $ echo "test"
test
pi@raspberrypi ~ $ echo -n "test"
testpi@raspberrypi ~ $ echo -ne "test"
testpi@raspberrypi ~ $ echo -ne "test\n"
test
pi@raspberrypi ~ $ 

Re: Bash, append \n to a string

Posted: Thu Sep 05, 2013 2:20 pm
by jojopi
ukscone wrote:[…] rather than if the echo implementation decides to put them in.
That is an important point. The behaviour of echo has always been implementation-defined with respect to backslashes and the -n option. Since the unification of POSIX:2001 and SUSv3, -e is actually forbidden unless preceded by -n, which remains implementation defined.

If you care about escapes or newlines, you are better to use printf(1):

Code: Select all

pi@tau ~ $ printf "hello " && printf "world\n"
hello world
pi@tau ~ $