将参数传递给 bash 函数时“$@”和“$*”之间的区别

bod*_*ydo 3 bash shell command-line arguments parameter-passing

我有之间很难理解的差异$@,并$*把它们传递给函数时。

这是示例:

function a {
    echo "-$1-" "-$2-" "-$3-";
}

function b {
    a "$@"
}

function c {
    a "$*"
}
Run Code Online (Sandbox Code Playgroud)

如果调用:

$ b "hello world" "bye world" "xxx"
Run Code Online (Sandbox Code Playgroud)

它打印:

-hello world- -bye world- -xxx-
Run Code Online (Sandbox Code Playgroud)

如果调用:

$ c "hello world" "bye world" "xxx"
Run Code Online (Sandbox Code Playgroud)

它打印:

$ c "hello world" "bye world" "xxx"
-hello world bye world xxx- -- --
Run Code Online (Sandbox Code Playgroud)

发生了什么?我无法理解差异和出了什么问题。

ric*_*ici 5

$*和之间没有区别$@。它们都会导致参数列表被全局扩展和分词,因此您不再了解原始参数。你几乎不想要这个。

"$*"结果是一个字符串,它是使用第一个字符$IFS作为分隔符(默认为空格)连接的所有参数。这有时是您想要的。

"$@"每个参数产生一个字符串,既不是分词也不是 glob-expanded。这通常是您想要的。