WORD为变量时,为什么在`case WORD in`语句中不会发生WORD的字段拆分?

Why does field splitting of WORD not occur in `case WORD in` statement when WORD is a variable?

Shell 脚本:

#!/bin/sh
a="foo  bar"

case $a in
    "foo  bar")
        echo case 1
        ;;
esac

case foo  bar in
    "foo  bar")
        echo case 2
        ;;
esac

使用 bash 执行此操作会导致以下输出和错误。

case 1
foo: line 10: syntax error near unexpected token `bar'
foo: line 10: `case foo  bar in'

使用 dash 执行此操作:

case 1
foo: 10: foo: Syntax error: word unexpected (expecting "in")` leads to the following output and error.

我不明白为什么第一个 case 语句成功但第二个语句不成功。

根据 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 的 POSIX 文档,在任何一种情况下都会发生字段拆分,因此在 $a 扩展为 foo bar 之后,第一个 case 语句,它应该等同于第二个。

所以两者都应该失败。为什么第一个 case 语句成功?

分词 在第一种情况下对 case 中使用的 word 进行分词陈述。来自 POSIX:

案例条件构造

The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) that is matched by the string resulting from the tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal of the given word.

所以不管你是否引用这个词,它都不会被展开并且没有引号是安全的。

case $a in  
   ...
esac

case "$a" in    
   ...
esac

将按预期工作。

显然,这不等同于第二个示例,在第二个示例中,您在 case 语句中有 两个 个单词。