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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7301780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:42:56  来源:igfitidea点击:

Put results of mysql command line query into bash script variable

mysqlbash

提问by Jordan Lev

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=...". If I just hard-code a table name into that it works fine, like this:

给我带来麻烦的那一行是“cmdRes=...”。如果我只是硬编码一个表名,它可以正常工作,如下所示:

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. 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.

但是当我在那个东西里面有一个 $variable 时,我无法理解发生了什么/为什么/发生了什么。基于对许多其他类似但不同的问题的回答,我尝试将字符串的不同部分放入不同的变量中以减少引用,我尝试过单引号、双引号、反斜杠、双单-双引号、花括号、运行 eval 等——但没有任何效果。

Thanks for any help you can provide.

感谢您的任何帮助,您可以提供。

回答by paulsm4

The problem is that the shell won't expand anything inside the single quotes (').

问题是外壳不会在单引号 (') 内展开任何内容。

One possible solution:

一种可能的解决方案:

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