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.
-
- Posts: 75
- Joined: Thu Mar 15, 2012 7:27 pm
Re: Bash, append \n to a string
I'm not sure what you're doing wrong \n is working for me:
Richard S.
Perhaps you could post some samples of your script code for checking.#!/bin/bash
string="Hello"
append="\ne\nl\nl\no"
string="$string""$append"
echo -e $string
Richard S.
-
- Posts: 75
- Joined: Thu Mar 15, 2012 7:27 pm
Re: Bash, append \n to a string
This is where it happens, echo is OK
Echo to the data variable is the solution?
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.
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
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.
-
- Posts: 75
- Joined: Thu Mar 15, 2012 7:27 pm
Re: Bash, append \n to a string
worksif [ ${#data} -gt 0 ]; then
data="$data\n"
fi
data="$data$sensor,$temp"
done
echo -e $data
data=$(echo -e $data)

Re: Bash, append \n to a string
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
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.ukscone wrote:[…] rather than if the echo implementation decides to put them in.
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 ~ $