把MySQL命令行查询结果为bash脚本变量 [英] Put results of mysql command line query into bash script variable
问题描述
我有一个真的很难搞清楚如何获得一个MySQL查询的结果为一个bash shell脚本变量。
I am having a really difficult time figuring out how to get the results of a mysql query into a bash shell script variable.
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
这是给我的麻烦线是cmdRes = ...。如果我只是硬code表名称为它工作得很好,是这样的:
The line that is giving me the trouble is "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"')
但我不能换我的头围绕如何/为什么/什么是对,当我有那个东西里面$变量去。基于解答了很多其他类似的,但是,不同的问题,我已经试过把字符串转换成不同的变量的不同部分,以减少报价,我已经试过单引号,双引号,反斜杠,双单双引号,花括号,运行的eval,等等 - 但没有什么工作
But I cannot wrap my head around how/why/what is going on when I have a $variable inside that thing. 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.
感谢您的帮助,您可以提供。
Thanks for any help you can provide.
推荐答案
的问题是,外壳不会扩大单引号里的任何东西(')
The problem is that the shell won't expand anything inside the single quotes (').
一个可能的解决方案:
cmdRes=$($mysqlCmd -e "SHOW DATABASES LIKE '$testDBName'")
这篇关于把MySQL命令行查询结果为bash脚本变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!