honda4life
Posts: 75
Joined: Thu Mar 15, 2012 7:27 pm

Bash, append \n to a string

Sun Aug 25, 2013 8:32 am

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.

User avatar
redhawk
Posts: 3465
Joined: Sun Mar 04, 2012 2:13 pm
Location: ::1

Re: Bash, append \n to a string

Sun Aug 25, 2013 9:42 am

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.

honda4life
Posts: 75
Joined: Thu Mar 15, 2012 7:27 pm

Re: Bash, append \n to a string

Sun Aug 25, 2013 11:40 am

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.

honda4life
Posts: 75
Joined: Thu Mar 15, 2012 7:27 pm

Re: Bash, append \n to a string

Sun Aug 25, 2013 11:55 am

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

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

User avatar
ukscone
Forum Moderator
Forum Moderator
Posts: 4279
Joined: Fri Jul 29, 2011 2:51 pm
Contact: Website

Re: Bash, append \n to a string

Thu Sep 05, 2013 12:31 pm

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 ~ $ 

User avatar
jojopi
Posts: 3406
Joined: Tue Oct 11, 2011 8:38 pm

Re: Bash, append \n to a string

Thu Sep 05, 2013 2:20 pm

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 ~ $ 

Return to “Other programming languages”