将mysql查询输出存储到shell变量中 [英] Store mysql query output into a shell variable

查看:624
本文介绍了将mysql查询输出存储到shell变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个变量来保存从数据库中检索到的结果.到目前为止,这基本上是我一直没有成功的尝试.

myvariable=$(mysql database -u $user -p $password | SELECT A, B, C FROM table_a)

如您所见,我对bash命令的理解不是很好.

解决方案

我对MySQL命令行界面了解不多,但是假设您只需要帮助,可以尝试像这样交换命令所以:

myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password)

将字符串回显到MySQL.或者,您可能会更喜欢并使用一些新的bash功能(here字符串)

myvariable=$(mysql database -u $user -p$password<<<"SELECT A, B, C FROM table_a")

结果相同(假设您使用的是最新的bash版本),而没有涉及echo.

请注意,-p $ password不是错字,而是MySQL期望通过命令行输入密码的方式(选项和值之间没有空格).

请注意,myvariable将包含MySQL在标准输出上输出的所有内容(通常是除错误消息以外的所有内容),包括任何和所有列标题,ASCII美术框架等,可能不是您想要的.


如前所述,MySQL似乎有一个-e参数,我肯定会这么做.

I need a variable to hold results retrieved from the database. So far this is basically what I'm trying with no success.

myvariable=$(mysql database -u $user -p $password | SELECT A, B, C FROM table_a)

My understanding of bash commands is not very good as you can see.

解决方案

I don't know much about the MySQL command line interface, but assuming you only need help with the bashing, you should try to either swap the commands around like so:

myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password)

which echos the string into MySQL. Or, you can be more fancy and use some new bash-features (the here string)

myvariable=$(mysql database -u $user -p$password<<<"SELECT A, B, C FROM table_a")

resulting in the same thing (assuming you're using a recent enough bash version), without involving echo.

Please note that the -p$password is not a typo, but is the way MySQL expects passwords to be entered through the command line (with no space between the option and value).

Note that myvariable will contain everything that MySQL outputs on standard out (usually everything but error messages), including any and all column headers, ASCII-art frames and so on, which may or may not be what you want.

EDIT:
As has been noted, there appears to be a -e parameter to MySQL, I'd go for that one, definitely.

这篇关于将mysql查询输出存储到shell变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆