比方说,你有一个Bash别名:
alias rxvt='urxvt'
这很好。
然而:
alias rxvt='urxvt -fg '#111111' -bg '#111111''
不管用,也不管用:
alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''
那么,一旦有转义引号,如何在字符串中匹配开始和结束引号呢?
alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''
看起来很笨拙,但如果允许像这样连接它们,它将表示相同的字符串。
恕我直言,真正的答案是你不能在单引号字符串中转义单引号。
它是不可能的。
如果我们假设使用bash。
从bash手册…
Enclosing characters in single quotes preserves the literal value of each
character within the quotes. A single quote may not occur
between single quotes, even when preceded by a backslash.
您需要使用其他字符串转义机制之一"或\
没有什么神奇的关于别名要求它使用单引号。
以下两种方法都可以在bash中工作。
alias rxvt="urxvt -fg '#111111' -bg '#111111'"
alias rxvt=urxvt\ -fg\ \'#111111\'\ -bg\ \'#111111\'
后者使用\来转义空格字符。
#111111要求单引号也没有什么神奇之处。
下面的选项实现了与其他两个选项相同的结果,因为rxvt别名按预期工作。
alias rxvt='urxvt -fg "#111111" -bg "#111111"'
alias rxvt="urxvt -fg \"#111111\" -bg \"#111111\""
您还可以直接逃避麻烦的#
alias rxvt="urxvt -fg \#111111 -bg \#111111"
恕我直言,真正的答案是你不能在单引号字符串中转义单引号。
它是不可能的。
如果我们假设使用bash。
从bash手册…
Enclosing characters in single quotes preserves the literal value of each
character within the quotes. A single quote may not occur
between single quotes, even when preceded by a backslash.
您需要使用其他字符串转义机制之一"或\
没有什么神奇的关于别名要求它使用单引号。
以下两种方法都可以在bash中工作。
alias rxvt="urxvt -fg '#111111' -bg '#111111'"
alias rxvt=urxvt\ -fg\ \'#111111\'\ -bg\ \'#111111\'
后者使用\来转义空格字符。
#111111要求单引号也没有什么神奇之处。
下面的选项实现了与其他两个选项相同的结果,因为rxvt别名按预期工作。
alias rxvt='urxvt -fg "#111111" -bg "#111111"'
alias rxvt="urxvt -fg \"#111111\" -bg \"#111111\""
您还可以直接逃避麻烦的#
alias rxvt="urxvt -fg \#111111 -bg \#111111"
如果你已经安装了GNU Parallel,你可以使用它的内部引用:
$ parallel --shellquote
L's 12" record
<Ctrl-D>
'L'"'"'s 12" record'
$ echo 'L'"'"'s 12" record'
L's 12" record
从版本20190222,你甚至可以——shellquote多次:
$ parallel --shellquote --shellquote --shellquote
L's 12" record
<Ctrl-D>
'"'"'"'"'"'"'L'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'s 12" record'"'"'"'"'"'"'
$ eval eval echo '"'"'"'"'"'"'L'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'s 12" record'"'"'"'"'"'"'
L's 12" record
它将在所有受支持的shell(不仅仅是bash)中引用该字符串。