为什么`ls [0-9]` 找到了一个名为`[0-9]` 的文件,更糟糕的是,在`touch 1` 之后却找不到?

Ped*_*o A 0 bash wildcards

$ mkdir temp && cd temp
$ ls [0-9]
ls: cannot access '[0-9]': No such file or directory
$ touch \[0-9\]
$ ls [0-9]
'[0-9]'
$ touch 1
$ ls
 1  '[0-9]'
$ ls [0-9]
1
Run Code Online (Sandbox Code Playgroud)

我觉得这种行为非常令人惊讶。对我来说,[0-9]glob 模式应该只匹配名称由单个数字组成的文件。但它有时也会匹配一个名为[0-9]自身的文件。

这是 bash 中 glob 扩展的错误吗?

我可以禁用它,以便[0-9]永远不匹配[0-9](因为它不应该)?

zev*_*zek 6

您应该使用以下failglob选项设置选项shopt -s failglob

$ ls [2-9]
ls: cannot access '[2-9]': No such file or directory
$ touch '[2-9]'
$ ls [2-9]
[2-9]
$ shopt -s failglob
$ ls [2-9]
bash: no match: [2-9]
Run Code Online (Sandbox Code Playgroud)

额外问题:为什么倒数第二个 ls 打印前导空格?

由于GNU ls新的“用户友好”默认引用样式

$ touch 1
$ unset QUOTING_STYLE # use the default
$ ls
 1  '[2-9]'
$ QUOTING_STYLE=literal ls
1  [2-9]
$ ls --quoting-style=literal
1  [2-9]
Run Code Online (Sandbox Code Playgroud)