1

使用 BASH Parameter Expansion时,可以引用/转义变量扩展为的字符串,这可以正常工作,除非使用单引号并且整个变量用双引号转义:

$ echo "${var:-\\a}"
\a # ok
$ echo "${var:-"\\a"}"
\a # ok
$ echo "${var:-$'\\a'}"
\a # ok
$ echo "${var:-'\a'}"
'\a' # wtf?

有趣的是,$' '报价正常工作,而' '没有。如果变量本身没有被引用,单引号开始正常工作:

$ echo ${var:-'\a'}
\a

$var但是,如果它本身包含空白字符,则可能会导致其他问题。

这种不一致有什么好的理由吗?

4

1 回答 1

1

我认为这是源代码中最相关的引用(y.tab.c):

  /* Based on which dolstate is currently in (param, op, or word),
     decide what the op is.  We're really only concerned if it's % or
     #, so we can turn on a flag that says whether or not we should
     treat single quotes as special when inside a double-quoted
     ${...}. This logic must agree with subst.c:extract_dollar_brace_string
     since they share the same defines. */
  /* FLAG POSIX INTERP 221 */

  [...]

  /* The big hammer.  Single quotes aren't special in double quotes.  The
     problem is that Posix used to say the single quotes are semi-special:
     within a double-quoted ${...} construct "an even number of
     unescaped double-quotes or single-quotes, if any, shall occur." */
  /* This was changed in Austin Group Interp 221 */

我不清楚为什么单引号并不特别,但这似乎是在更改之前经过长时间(并且有人告诉我有争议)辩论后做出的有意识的选择。但事实是(如果我总结正确的话),这里的单引号只是常规字符,而不是句法引号,并且按字面意思对待。

于 2018-12-14T20:55:04.933 回答