将参数传递给bash函数时,“$ @”和“$ *”之间的区别
问题描述:
将参数传递给函数时,我很难理解[email protected]
和$*
之间的区别。
这里是例子:
function a {
echo "-$1-" "-$2-" "-$3-";
}
function b {
a "[email protected]"
}
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- -- --
发生了什么事?我无法理解差异,出了什么问题。
答
$*
和[email protected]
之间没有区别。它们都会导致参数列表被全局扩展和分词,因此您不再对原始参数有任何了解。你几乎不想要这个。
"$*"
产生单个字符串,这是使用$IFS
的第一个字符作为分隔符(默认情况下为空格)连接的所有参数。这偶尔是你想要的。
"[email protected]"
每个参数产生一个字符串,既不是分词也不是glob扩展。这通常是你想要的。
+0
谢谢,我发现它并且不加理会。对于那个很抱歉。我现在编辑了我的问题。 – bodacydo
“$ @”与有参数一样多的字符串; “$ *”是单个字符串。这个问题有很多问题 - 我会很快找到。 –
谢谢@JonathanLeffler,这是一个很好的阅读。 – bodacydo