0

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;
    }
3
  • 1
    mysql -Nse 'show tables' DATABASE | xargs Commented Mar 23, 2017 at 17:36
  • What is the output of the mysql command by itself? That said, always use IFS= read -r table unless you have a compelling reason not to. You might also want to check the output of echo "$alltables" | od to get a better idea of exactly what characters are in the value. Commented Mar 23, 2017 at 19:17
  • the output is tables name connected with \n\r, and that was the culprit. Commented Mar 24, 2017 at 8:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

the checking snippet didn't display \r, but it worked, thank you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.