使 ZSH 将变量作为空格分隔的参数传递

Xer*_*rus 2 bash zsh environment-variables sh

我想创建一个在 zsh 和 bash 中工作的别名,但奇怪的是 zsh 尝试将不带引号的变量作为单个参数传递:

\n
\xe2\x9d\xaf zsh -f\ngrasshopper% LS_OPTIONS="-l -a" && ls $LS_OPTIONS\nls: invalid option -- \' \'\nTry \'ls --help\' for more information.\ngrasshopper% bash --norc\nbash-5.1$ LS_OPTIONS="-l -a" && ls $LS_OPTIONS\ntotal 0\ndrwxr-xr-x  2 janekf janekf   40 28. Nov 14:02 .\ndrwxrwxrwt 24 root   root   2400 28. Nov 16:41 ..\n
Run Code Online (Sandbox Code Playgroud)\n

有办法阻止这种情况吗?

\n

另请参阅在 zsh 中使用变量作为命令参数,但答案是 zsh 特定的。

\n

che*_*ner 5

如果您想要同时适用于zsh和 的东西bash,请使用数组。

LS_OPTIONS=(-l -a) && ls "${LS_OPTIONS[@]}"
Run Code Online (Sandbox Code Playgroud)

您可以设置SH_WORD_SPLIT选项 inzsh以使参数扩展经历分词,就像 中 一样bash,但未加引号的扩展也bash受到路径名扩展的影响,因此我不建议使用它们。