简体   繁体   English

转义单引号内单引号内双引号内

[英]Escape single quote inside single quote inside double quote

I'm trying to run a query on a remote server from by bash script.我正在尝试通过 bash 脚本在远程服务器上运行查询。 Problem is, I have to use single quotes inside of the query which already has surrounding single quotes.问题是,我必须在已经有单引号的查询中使用单引号。

My code:我的代码:

# 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\"\'\"'"

The error I'm seeing upon running this code:我在运行此代码时看到的错误:

bash: -c: line 0: unexpected EOF while looking for matching `"'
bash: -c: line 1: syntax error: unexpected end of file

Example of working MYSQL query:工作 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;'

The simplest workaround is to use a context where you don't quote the expression at all.最简单的解决方法是使用根本不引用表达式的上下文。

Using a here document will tie up the standard input of ssh , but in this case it seems acceptable (or perhaps even desirable).使用 here 文档会占用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

The parameter expansion ${line//\\`/\\\\\\`} is a Bash-only feature so this depends on the remote shell being Bash.参数扩展${line//\\`/\\\\\\`}是仅 Bash 的功能,因此这取决于 Bash 的远程 shell。

After the comment by @KamilCuk it got me thinking about the escape characters and running the code without the SSH.在@KamilCuk 发表评论后,我开始考虑转义字符并在没有 SSH 的情况下运行代码。

I have rewritten the code to only contain " or ' which results in:我已将代码重写为仅包含"'导致:

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

Also removing the ` helped, as anything between that character will be executed as a command.还删除了 `help,因为该字符之间的任何内容都将作为命令执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM