在BASH参数扩展期间单引号行为不一致的原因?

时间:2018-12-14 19:12:45

标签: bash shell quotes quoting parameter-expansion

使用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本身包含空格字符,则可能导致其他问题。

是否存在这种不一致的充分理由?

1 个答案:

答案 0 :(得分: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 */

在我看来,为什么并不特别,但似乎是在更改之前进行了很长时间(而且我被告知存在争议)的辩论之后做出的有意识选择。但是事实是(如果我正确地概括了这一点),这里的单引号只是常规字符,而不是句法引号,并且按字面意义处理。