在运行 rake 任务时解决 "zsh: no matches found" 错误

macOS 现在默认使用 zsh 作为 shell,这意味着这个问题相当频繁地出现。

zsh 中:

% bin/rake plugin:spec[discourse-solved]
zsh: no matches found: plugin:spec[discourse-solved]
为什么会发生这种情况?

这是因为方括号被解释为 glob 模式。在 bash 中,如果 glob 模式无法匹配,命令仍会执行并正常工作。相比之下,zsh 会抛出错误并不执行 rake

举例说明,在 bash 中:

○ → echo bin/rake plugin:spec[discourse-solved]
bin/rake plugin:spec[discourse-solved]

○ → touch plugin:specd

○ → echo bin/rake plugin:spec[discourse-solved]
bin/rake plugin:specd

你可以通过在 bash 中启用 failglob 选项来复现 zsh 的行为:

○ → echo bin/rake plugin:spec[discourse-solved]
bin/rake plugin:spec[discourse-solved]

○ → shopt -s failglob

○ → echo bin/rake plugin:spec[discourse-solved]
bash: no match: plugin:spec[discourse-solved]

(感谢 @j.jaffeux@pmusaraj 为我指明正确方向,以及 @supermathie 提供的 bash 示例 :heart_eyes:

若要按预期工作,你需要将整个 rake 参数用引号包裹:

% bin/rake "plugin:spec[discourse-solved]"

哎呀。这听起来可能会给那些不太可能知道如何排查问题的人带来不少麻烦。希望他们能找到这个主题。

这通常没问题——脚本只需指定 bash 即可避免任何麻烦。

确实如此。我想这就是为什么我所有的 bash 脚本都以 #!/usr/bin/env bash 开头,尽管我并不指望它们会在 Mac 上运行 :wink:

或者,您可以在 ZSH 配置中添加一个别名。:slight_smile:
这在 Linux 上有效,因此在 macOS 上可能也有效。

alias rake='noglob rake'