bash 在 shell 变量中转义单引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14339460/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:15:35  来源:igfitidea点击:

escape single quote in shell variable

bashshell

提问by Dien Nguyen

I wrote a bash script to insert values to sqlitedatabase. The command is as follow

我编写了一个 bash 脚本来将值插入到sqlite数据库中。命令如下

sqlite3 ${db_name} "insert into ${table_name} (${column1},${column2}) values ('$f1','$f2');"

This command works fine until f1variable contains a single quote

此命令工作正常,直到f1变量包含单引号

# e.g f1="I'm just kidding"
# the command reported error
Error: near "m": syntax error

May someone please show me how can we escape the single quote inside the variable? Any recommendations are appreciated. Thanks!

有人可以告诉我如何转义变量中的单引号吗?任何建议表示赞赏。谢谢!

回答by peteches

from bash you can use ${varname//x/y} to replace all instances of x with y in the varname variable.

在 bash 中,您可以使用 ${varname//x/y} 在 varname 变量中用 y 替换 x 的所有实例。

sqlite3 ${db_name} "insert into ${table_name} (${column1},${column2}) values ('${f1//\'/\'}','${f2//\'/\'}');"

will replace any ' with \' though @ignacioVazquez-Abrams has the best answer as php perl python all have modules to help sanitise input.

尽管@ignacioVazquez-Abrams 有最好的答案,但将用 \ 替换任何 ',因为 php perl python 都有帮助清理输入的模块。

回答by glenn Hymanman

To escape a single quote for SQL, you double it (https://www.sqlite.org/faq.html#q14):

要为 SQL 转义单引号,请将其加倍(https://www.sqlite.org/faq.html#q14):

$ f1="I'm just kidding"
$ echo "${f1//\'/''}"
I''m just kidding
$ f2="no single quotes"
$ echo "${f2//\'/''}"
no single quotes

So

所以

sqlite3 ${db_name} "insert into ${table_name} (${column1},${column2}) values ('${f1//\'/''}','${f2//\'/''}');"

回答by JoaoBiriba

You could use \

你可以使用\

f1="I\'m just kidding"