2

Say when I run mysql -u user -p -e 'select id from db.users limit 1', I got:

+------+
| id   |
+------+
| 8434 |
+------+

When I redirect the output/stdout to some file, like mysql -u user -p -e 'select id from db.users limit 1' > /tmp/a.txt, then I cat /tmp/a.txt, I got:

id
8434

So where do those little format strings go? Does it mean that mysql knows when it is redirected, so it returns a different format? I always thought a redirect(>) doesn't concern the previous command, that it doesn't have to know if or where its output is redirected. Or is it another explanation?

2 Answers 2

4

You'll get same output by adding -B option

    mysql -B -u user -p -e 'select id from db.users limit 1'

then you'll see

 id       
 8434 

Also, mysql command tests if the cout is tty or not, to switch output formatting. As you can see in the source code of mysql command.

4
  • -B means printing results using tab as the column separator, so it means the output of mysql -e 'blahblah' is separated by tab and new line, instead those '|' and '+' and '-'. Anyway, my question is, why the output format is different with & without a redirect. Does this mean mysql knows when its output is redirected to somewhere else? Jan 7, 2015 at 4:17
  • @DeanWinchester "Does this mean mysql knows when its output is redirected to somewhere else" -> yes, mysql knows. I've edited the answer.
    – turutosiya
    Jan 7, 2015 at 4:46
  • You're right:). isatty can test it, it's just about file descriptors. If there's a redirected, or a pipe, then the file descriptor is not 1 anymore. And I edited you answer a bit, something about -B is incorrect Jan 7, 2015 at 6:09
  • @DeanWinchester Thanks for the suggestion! it seems that your suggestion was rejected by 3 other users, then I've updated with your suggestion.
    – turutosiya
    Jan 7, 2015 at 10:38
1

To get the same fancy table format when redirecting, add the -t flag or --table to your mysql command.

+----+--------+
| id | name   |
+----+--------+
|  1 | Quincy |
+----+--------+

As for your question, mysql uses isatty under the hood to know if you are redirecting output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.