BASH 参数扩展期间单引号行为不一致的原因?
Reason for inconsistent behavior of single quotes during BASH parameter expansion?
当使用 BASH Parameter Expansion 时,变量扩展成的字符串可以是 quoted/escaped,这工作正常,除非使用单引号并且整个变量以双引号转义报价:
$ 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
本身包含空白字符,这可能会导致其他问题。
这种不一致有什么充分的理由吗?
我认为这是源代码中最相关的引用 (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 */
我不是很清楚为什么单引号并不特别,但这似乎是经过长时间(有人告诉我有争议的)辩论之后做出的有意识的选择改变。但事实是(如果我总结的没错的话),这里的单引号只是普通字符,不是句法引号,按字面意思对待。
当使用 BASH Parameter Expansion 时,变量扩展成的字符串可以是 quoted/escaped,这工作正常,除非使用单引号并且整个变量以双引号转义报价:
$ 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
本身包含空白字符,这可能会导致其他问题。
这种不一致有什么充分的理由吗?
我认为这是源代码中最相关的引用 (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 */
我不是很清楚为什么单引号并不特别,但这似乎是经过长时间(有人告诉我有争议的)辩论之后做出的有意识的选择改变。但事实是(如果我总结的没错的话),这里的单引号只是普通字符,不是句法引号,按字面意思对待。