转义单引号内的单引号

时间:2019-12-05 10:16:09

标签: bash quotes double-quotes single-quotes

我正在尝试通过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;'

2 个答案:

答案 0 :(得分:1)

最简单的解决方法是在根本不引用表达式的情况下使用上下文。

使用此处文档会占用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。

答案 1 :(得分:0)

@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

还要删除`help,因为该字符之间的任何内容都将作为命令执行。