Today I needed to write a quick bash script to send a monthly report to a colleague. The report required running a few MySQL queries and then concatenating the output into a file, and e-mailing it to them. Normally when you run a MySQL query from the command line, the output is shown within a handy ASCII table.
# mysql --table -e "SELECT 1+1";
+-----+
| 1+1 |
+-----+
| 2 |
+-----+
Unfortunately, it seems that when you redirect the output to a file, the ASCII formatting is lost…
# mysql -e "SELECT 1+1" > /tmp/test
# cat /tmp/test
1+1
2
It took me a while to find it, but the solution is really simple. Simply add the –table parameter to the MySQL command:
# mysql --table -e "SELECT 1+1" > /tmp/test
# cat /tmp/test
+-----+
| 1+1 |
+-----+
| 2 |
+-----+
And that’s it! Hopefully this post will save someone else some time in the future.