bash 脚本中 $@ 和 $* 的区别

bash 脚本中 $@ 和 $* 的区别

$@和之间有哪些区别$*?例如,我在这里没有看到任何区别:

#! /bin/bash
echo with star: $*
echo with at sign: $@

答案1

$@不加引号时,和没什么区别$*。 都等于$1 $2… 但不要这么做。

使用双引号,"$@"将每个元素扩展为参数:

"$1" "$2"

while"$*"扩展为合并为一个参数的所有元素:

"$1c$2c..."

其中c是 的第一个字符IFS。如果取消设置IFSc则将为空格。

你几乎总是想要"$@"。数组也是如此:"${myarray[@]}"

答案2

@sputnick 的答案是正确的。举个例子来说明:\

# use two positional parameters, each with whitespace
set -- "one two" "three four"

# demonstrate the various forms with the default $IFS
echo '$*:'
printf ">%s<\n" $*
echo '$@:'
printf ">%s<\n" $@
echo '"$*":'
printf ">%s<\n" "$*"
echo '"$@":'
printf ">%s<\n" "$@"

# now with a custom $IFS
(
IFS=:
echo '$*:'
printf ">%s<\n" $*
echo '$@:'
printf ">%s<\n" $@
echo '"$*":'
printf ">%s<\n" "$*"
echo '"$@":'
printf ">%s<\n" "$@"
)

输出

$*:
>one<
>two<
>three<
>four<
$@:
>one<
>two<
>three<
>four<
"$*":
>one two three four<
"$@":
>one two<
>three four<
$*:
>one two<
>three four<
$@:
>one two<
>three four<
"$*":
>one two:three four<
"$@":
>one two<
>three four<

相关内容