在双引号内的单引号内转义单引号
Escape single quote inside single quote inside double quote
我正在尝试 运行 通过 bash 脚本在远程服务器上进行查询。问题是,我必须在已经包含单引号的查询中使用单引号。
我的代码:
# note: $line has ` in it, as this is a SQL query
ssh server "mysql --defaults-extra-file=$SQL_CREDS_FILE $R_DB $t -e '$line INTO OUTFILE \"\'\"$DIR/$tbl_count.csv\"\'\" FIELDS TERMINATED BY \"\'\",\"\'\" ENCLOSED BY \"\'\"\"\'\" LINES TERMINATED BY \"\'\"\n\"\'\"'"
我在 运行 执行此代码时看到的错误:
bash: -c: line 0: unexpected EOF while looking for matching `"'
bash: -c: line 1: syntax error: unexpected end of file
工作示例 MYSQL 查询:
mysql -u user -pPassword database -e 'select `id`,`title`,`name`,`description`,`icon`,`creation_date` as `created_at`,`mutation_date` as `created_at` from achievement;'
@KamilCuk 发表评论后,我开始思考转义字符和 运行 没有 SSH 的代码。
我已将代码重写为仅包含 "
或 '
,结果为:
ssh server "mysql --defaults-extra-file=$SQL_CREDS_FILE $R_DB -e \"$line INTO OUTFILE '$DIR/$tbl_count.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n'\"" < /dev/null
删除 ` 也有帮助,因为该字符之间的任何内容都将作为命令执行。
最简单的解决方法是使用根本不引用表达式的上下文。
使用此处文档会占用 ssh
的标准输入,但在这种情况下似乎可以接受(甚至可能是可取的)。
ssh server <<____HERE
# Guessing $R_DB contains "database"
# Guessing $t contains your credentials ...?
# Guessing $DIR contains a directory name
# Guessing $tbl_count contains a file name
# Guessing $line contains your actual query
mysql "$R_DB" $t -e "${line//\`/\\`} INTO OUTFILE '$DIR/$tbl_count.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n'"
____HERE
参数扩展 ${line//\`/\\`}
是 Bash 独有的功能,因此这取决于远程 shell 是 Bash。
我正在尝试 运行 通过 bash 脚本在远程服务器上进行查询。问题是,我必须在已经包含单引号的查询中使用单引号。
我的代码:
# note: $line has ` in it, as this is a SQL query
ssh server "mysql --defaults-extra-file=$SQL_CREDS_FILE $R_DB $t -e '$line INTO OUTFILE \"\'\"$DIR/$tbl_count.csv\"\'\" FIELDS TERMINATED BY \"\'\",\"\'\" ENCLOSED BY \"\'\"\"\'\" LINES TERMINATED BY \"\'\"\n\"\'\"'"
我在 运行 执行此代码时看到的错误:
bash: -c: line 0: unexpected EOF while looking for matching `"'
bash: -c: line 1: syntax error: unexpected end of file
工作示例 MYSQL 查询:
mysql -u user -pPassword database -e 'select `id`,`title`,`name`,`description`,`icon`,`creation_date` as `created_at`,`mutation_date` as `created_at` from achievement;'
@KamilCuk 发表评论后,我开始思考转义字符和 运行 没有 SSH 的代码。
我已将代码重写为仅包含 "
或 '
,结果为:
ssh server "mysql --defaults-extra-file=$SQL_CREDS_FILE $R_DB -e \"$line INTO OUTFILE '$DIR/$tbl_count.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n'\"" < /dev/null
删除 ` 也有帮助,因为该字符之间的任何内容都将作为命令执行。
最简单的解决方法是使用根本不引用表达式的上下文。
使用此处文档会占用 ssh
的标准输入,但在这种情况下似乎可以接受(甚至可能是可取的)。
ssh server <<____HERE
# Guessing $R_DB contains "database"
# Guessing $t contains your credentials ...?
# Guessing $DIR contains a directory name
# Guessing $tbl_count contains a file name
# Guessing $line contains your actual query
mysql "$R_DB" $t -e "${line//\`/\\`} INTO OUTFILE '$DIR/$tbl_count.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n'"
____HERE
参数扩展 ${line//\`/\\`}
是 Bash 独有的功能,因此这取决于远程 shell 是 Bash。