Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings in bash overwrites them

Tags:

bash

I'm parsing query results from a mysql command (with the --table parameter)

local records=`echo "${query}" | $MYSQL -u $MyUSER -h $MyHOST -p$MyPASS --table`

The query is run successfully, and I receive good data.

Then I iterate over this data:

for data in $records ;
do
    test+=$data
done

The code is more extensive, but this is basically it. Bash sees every space as a separator though, and that's a problem for text fields.

So I just concatenate them. But when I feed bash this data:

*URL*
host:
test.url.com
pass:
anothertest

http://www.test.com

It concatenates it to something like:

pass:test.url.com.com

As if it's not concatenating, but overwriting. Is this maybe some carriage return problem?

like image 261
skerit Avatar asked Sep 10 '12 20:09

skerit


3 Answers

I had the same issue with the stderr output retrieved from the curl command. I found that the output contains carriage return that needs to be removed. For the example above this could be done using the tr tool:

for data in $records ;
do
    data=$(echo "$data" | tr -d '\r')
    test+="$data"
done
like image 66
cweigel Avatar answered Oct 29 '22 09:10

cweigel


Check that you use Unix line endings. Using Windows line endings caused the same behavior for me, overwriting strings.

like image 27
fdermishin Avatar answered Oct 29 '22 09:10

fdermishin


Make sure you're using Bash 3 or later. The += operator in Bash can be used to manipulate an Array. It will use the current value of the IFS variable to split the tokens and add the value to the array.

Try: test="$test $data" to concatenate the data

like image 21
a.drew.b Avatar answered Oct 29 '22 10:10

a.drew.b