如何通过 bash shell 在 SQLite 中转义字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/766207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I escape characters in SQLite via bash shell?
提问by Tony
I am trying to send a query to SQLite from the command line using bash. I need to escape both single quotes and double quotes, and escape them so that bash does not misinterpret them. Here is a typical query:
我正在尝试使用 bash 从命令行向 SQLite 发送查询。我需要同时转义单引号和双引号,并转义它们以便 bash 不会误解它们。这是一个典型的查询:
select * from contacts where source = "Nancy's notes";
How can I send this query from the command line? The basic syntax is something like this:
如何从命令行发送此查询?基本语法是这样的:
sqlite3.bin contacts.db 'select * from contacts where source = "Nancy's notes"'
But in this case, the shell misinterprets either the single or double quotes. I've tried escaping using both double and triple slashes but this doesn't work. I'm befuddled. Any suggestions?
但在这种情况下,shell 会误解单引号或双引号。我试过使用双斜线和三斜线进行转义,但这不起作用。我糊涂了。有什么建议?
回答by Jonathan Leffler
The trouble with MarkusQ's solution is knowing which characters are special inside double quotes - there are quite a lot of them, including back-ticks, dollar-open parenthesis, dollar-variable, etc.
MarkusQ 的解决方案的问题是知道哪些字符在双引号内是特殊的——有很多,包括反引号、美元开括号、美元变量等。
I would suggest it is better to enclose the string inside single quotes; then, each single quote inside the string needs to be replaced by the sequence quote, backslash, quote, quote:
我建议最好将字符串括在单引号内;然后,字符串中的每个单引号都需要替换为序列quote、反斜杠、quote、quote:
sqlite3.bin contacts.db 'select * from contacts
where source = "Nancy'\''s notes"'
The first quote in the replacement terminates the current single-quoted string; the backslash-quote represents a literal single quote, and the final quote starts a new single-quoted string. Further, this works with Bourne, Korn, Bash and POSIX shells in general. (C Shell and derivatives have more complex rules needing backslashes to escape newlines, and so on.)
替换中的第一个引号终止当前的单引号字符串;反斜杠引号表示文字单引号,最后的引号开始一个新的单引号字符串。此外,这通常适用于 Bourne、Korn、Bash 和 POSIX shell。(C Shell 和衍生产品有更复杂的规则,需要反斜杠来转义换行符,等等。)
回答by MarkusQ
If bash is your only problem, enclose the whole thing in double quotes and then escape anything that's special within bash double quotes with a single backslash. E.g.:
如果 bash 是您唯一的问题,请将整个内容括在双引号中,然后使用单个反斜杠将 bash 双引号中的任何特殊内容转义。例如:
sqlite3.bin contacts.db "select * from contacts where source = \"Nancy's notes on making $$$\""
回答by JohnMudd
Here I use two single quotes that sqlite interprets as one.
这里我使用了两个单引号,sqlite 将其解释为一个单引号。
sqlite3.bin contacts.db "select * from contacts where source = 'Nancy''s notes on making $$$'"

