为什么 $* 没有按预期工作?

ico*_*ast 1 bash arguments

我试图在函数中使用 $* 来扩展到函数中的所有命令行参数,但它给了我奇怪的行为:

$ function repeat() {
echo "$*"
}

$ repeat puts hello    # this gives me nothing at all
$ repeat "puts hello"  # this asks me for more input
repeat>
Run Code Online (Sandbox Code Playgroud)

为什么会那样做?

Sté*_*las 9

你在zsh,不是bash。

在zsh, repeat(受 启发csh repeat)是用于repeat命令的构造。

repeat 10 echo foo
Run Code Online (Sandbox Code Playgroud)

将 echo foo 10 次。

如果你想调用你的 repeat,你需要引用它,这样它就不会被当作repeat保留字。

$ echo $ZSH_VERSION
5.0.2
$ 'repeat'() echo "$*"
$ type -a repeat
repeat is a reserved word
repeat is a shell function
$ repeat 2 echo foo
foo
foo
$ "repeat" 2 x
2 x
Run Code Online (Sandbox Code Playgroud)

不过,最好为您的函数名称使用其他名称。