alizade alizade -4 years ago 289
Bash Question

bash concat strings in single variable using while read

In the following script, I try to get all tables name from a mysql database and I expect all table's name printed out, but no matter what I do or which method I use, it just doesn't work. the printed string I suppose are tables name overlapped on each other:


watchdoglescabularyrchygsey


What's wrong with this script?

mysql -Nse 'show tables' DATABASE |
{
while read table
do
alltables="$alltables $table"
done
echo $alltables;
}

Answer Source

Could it be that mysql separates the table names by \n\r instead of \n? The read would then read First Table, \rSecond Table, and so on. In most linux terminals \r causes the cursor to jump back to the start of the current line. ABC\r_ will be printed as _BC.

Checking for \r

Execute mysql -Nse 'show tables' DATABASE | sed 's:\r:\\r:' and look at the output. The control character \r will be printed as the literal string \r.

Deleting the \r

Insert a ... | tr -d '\r' | ... between the commands.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download