简体   繁体   English

将mysql命令行查询的结果放入bash脚本变量

[英]Put results of mysql command line query into bash script variable

I am having a really difficult time figuring out how to get the results of a mysql query into a bash shell script variable. 我很难弄清楚如何将mysql查询的结果转换为bash shell脚本变量。

testDBName="some_database_name"
mysqlUser="root"
mysqlPassword="password"
mysqlCmd="/Applications/MAMP/Library/bin/mysql -u $mysqlUser -p $mysqlPassword -B -N"
cmdRes=$($mysqlCmd -e 'SHOW DATABASES LIKE "$testDBName"') #THIS IS THE TROUBLESOME LINE
if [ "$cmdRes" = "" ]; then
    echo "Table does not exist"
else
    echo "Table already exists"
fi

The line that is giving me the trouble is "cmdRes=...". 给我带来麻烦的那一行是“ cmdRes = ...”。 If I just hard-code a table name into that it works fine, like this: 如果我只是将表名硬编码为可以正常工作的表名,如下所示:

cmdRes=$($mysqlCmd -e 'SHOW DATABASES LIKE "some_database_name"')

But I cannot wrap my head around how/why/what is going on when I have a $variable inside that thing. 但是当我在一个东西中有一个$ variable时,我无法全神贯注于如何/为什么/怎么回事。 Based on answers to a lot of other similar-but-different questions, I've tried putting different portions of the string into different variables to cut down on quoting, I've tried single quotes, double quotes, backslashes, double-single-double quotes, curly braces, running eval, etc. -- but nothing is working. 根据许多其他类似但不同的问题的答案,我尝试将字符串的不同部分放入不同的变量中以减少引号,我尝试了单引号,双引号,反斜杠,双单引号-双引号,花括号,运行eval等-但无济于事。

Thanks for any help you can provide. 感谢您的任何帮助,您可以提供。

The problem is that the shell won't expand anything inside the single quotes ('). 问题在于外壳程序不会在单引号(')内展开任何内容。

One possible solution: 一种可能的解决方案:

cmdRes=$($mysqlCmd -e "SHOW DATABASES LIKE '$testDBName'")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM