bash - 在命令中使用多个字符串定界符会导致 mysql 客户端/bash 脚本出现解析问题

标签 bash shell delimiter mysql

我正在尝试执行以下操作:

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/

相关文章:

linux - 在 bash 中使用 grep 的 for 循环语法

bash - 在 awk 中获取多个压缩文件的 FILENAME

linux - 如何在不评估命令的情况下从 shell 脚本向 shell 脚本编写命令

sql - 使用 oracle SQL 按分隔符位置拆分字符串

mysql - 'DELIMITER $$' 附近的错误

R cSplit 仅使用字符串中的第一个分隔符

bash - 将每个整数转换为简单的 ASCII 图形

java Runtime.getRuntime().exec() 无法运行命令

java - 在 Windows 上使用 Cygwin 排序时出现 "Input file specified two times."错误

linux - 日期/时间参数不正确