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

Difference between "$@" and "$*" when passing arguments to bash function

在将 $@$* 传递给函数时,我很难理解它们之间的区别。

示例如下:

function a {
    echo "--" "--" "--";
}

function b {
    a "$@"
}

function c {
    a "$*"
}

如果来电:

$ b "hello world" "bye world" "xxx"

它打印:

-hello world- -bye world- -xxx-

如果来电:

$ c "hello world" "bye world" "xxx"

它打印:

$ c "hello world" "bye world" "xxx"
-hello world bye world xxx- -- --

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

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

"$*" 生成一个字符串,它是使用 $IFS 的第一个字符作为分隔符(默认情况下为 space)连接的所有参数。这偶尔就是你想要的。

"$@" 导致每个参数一个字符串,既不分词也不扩展。这通常是您想要的。