A bit curious about `mysql -e` output format with & without redirect

时光毁灭记忆、已成空白 提交于 2019-12-24 12:51:56

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27812190/a-bit-curious-about-mysql-e-output-format-with-without-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!