我如何逃脱双引号内的双字符串在Bash?

例如,在我的shell脚本中

#!/bin/bash

dbload="load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"

我不能得到由'\"'与双引号括起来正确转义。我的变量不能使用单引号,因为我想使用变量$dbtable。


当前回答

使用反斜杠:

echo "\""     # Prints one " character.

其他回答

使用反斜杠:

echo "\""     # Prints one " character.

使用$"string"。

在这个例子中,它是,

dbload=$"load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"

注意(来自手册页):

双引号字符串前面加一个美元符号($"string")将导致该字符串根据当前语言环境进行翻译。如果当前区域设置为C或POSIX,则忽略美元符号。如果转换并替换了字符串,则替换的字符串会被双引号括起来。

在双引号前添加“\”来转义,而不是\

#! /bin/csh -f

set dbtable = balabala

set dbload = "load data local infile "\""'gfpoint.csv'"\"" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"\""' LINES TERMINATED BY "\""'\n'"\"" IGNORE 1 LINES"

echo $dbload
# load data local infile "'gfpoint.csv'" into table balabala FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "''" IGNORE 1 LINES

请记住,可以通过使用需要回显的字符的ASCII码来避免转义。

例子:

echo -e "This is \x22\x27\x22\x27\x22text\x22\x27\x22\x27\x22"
This is "'"'"text"'"'"

\x22是用于双引号的ASCII码(十六进制),\x27用于单引号。同样,您可以回显任何字符。

我想如果我们尝试用反斜杠回显上面的字符串,我们将需要一个混乱的两行反斜杠回显…:)

对于变量赋值,这是等价的:

a=$'This is \x22text\x22'
echo "$a"

# Output:
This is "text"

如果变量已经由另一个程序设置,您仍然可以使用sed或类似工具应用双引号/单引号。

例子:

b="Just another text here"
echo "$b"

 Just another text here

sed 's/text/"'\0'"/' <<<"$b" #\0 is a special sed operator
 Just another "0" here #this is not what i wanted to be

sed 's/text/\x22\x27\0\x27\x22/' <<<"$b"

 Just another "'text'" here #now we are talking. You would normally need a dozen of backslashes to achieve the same result in the normal way.

检查printf…

#!/bin/bash
mystr="say \"hi\""

不使用printf

echo -e $mystr

输出:说“hi”

使用printf

echo -e $(printf '%q' $mystr)

输出:say“hi”