我正在尝试执行以下操作:
OUTPUT=$(su - mysql -c "mysql --skip-column-names --raw --host=localhost --port=3306 --user=user --password=pass -e '显示变量,其中 variable_name = "max_connections"'")
然后通过本地框上的 shell 脚本执行此操作...但是,我得到了返回:
第 1 行的错误 1054 (42S22):“where 子句”中的未知列“max_connections”
如果我只是在盒子上本地执行命令,没有 bash:
sudo su - mysql -c "mysql --skip-column-names --raw --host=localhost --port=3306 --user=user --password=pass -e '显示变量在哪里variable_name = "max_connections"'"
我得到了预期的输出...所以好像 bash 解析出我的定界符是错误的? A related question revealed我不能为我的 variable_name
使用单引号分隔符,这看起来像 bash 试图将我的 "
解析为?
更新:演示单引号问题:
mysql@gossdevmydb0119.abn-sjl.ea.com:~
-> mysql --skip-column-names --raw --host=localhost --port=3306 --user=user --password=pass -e 'show variables where variable_name = 'max_connections''
ERROR 1054 (42S22) at line 1: Unknown column 'max_connections' in 'where clause'
mysql@gossdevmydb0119.abn-sjl.ea.com:~
-> mysql --skip-column-names --raw --host=localhost --port=3306 --user=user --password=pass -e 'show variables where variable_name = "max_connections"'
+-----------------+------+
| max_connections | 2000 |
+-----------------+------+
最佳答案
如果你确实需要 mysql 语句的引号,那么你可以使用 \"
。看看区别:
echo "mysql --raw -e 'show vars where var_name = "max_connections"'"
echo "mysql --raw -e 'show vars where var_name = \"max_connections\"'"
但是,请!:不要尝试在一个字符串中运行如此复杂的命令,这很难理解,也更难维护。分而治之,看看这段等效代码:
#!/bin/bash
User="user"
Pass="pass"
Options="--skip-column-names --raw --host=localhost --port=3306"
MoreOptions="--user=$User --password=$Pass"
RunStatement="-e 'show variables where variable_name = \"max_connections\"'"
echo "mysql --skip-column-names --raw --host=localhost --port=3306 --user=user --password=pass -e 'show variables where variable_name = "max_connections"'"
echo "mysql --skip-column-names --raw --host=localhost --port=3306 --user=user --password=pass -e 'show variables where variable_name = \"max_connections\"'"
echo "mysql $Options $MoreOptions $RunStatement"
三个 echo 命令中哪个更容易阅读和理解?
你的脚本命令将变成(假设变量设置如上)类似于:
OUTPUT="$(su - mysql -c "mysql $Options $MoreOptions $RunStatement")"
关于bash - 在命令中使用多个字符串定界符会导致 mysql 客户端/bash 脚本出现解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407750/