bash $* 和 $@ 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9915610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:53:55  来源:igfitidea点击:

The difference between $* and $@

bashshell

提问by thb

Possible Duplicate:
What the difference between “$@” and “$*” in bash?

可能的重复:
bash 中的“$@”和“$*”有什么区别?

For years and on dozens of occasions, I have hesitated between the use of $*and $@in shell scripts. Having read the applicable section of Bash's manpage over and over again, having tried both $*and $@, I more or less completely fail to understand the practical difference of application between the two variables. Can you enlighten me, please?

多年来,在几十次的情况下,我在 shell 脚本中使用$*和之间犹豫不决$@。一遍又一遍地阅读 Bash 手册页的适用部分,尝试了$*$@,我或多或少完全无法理解这两个变量之间的实际应用差异。你能帮我解惑吗?

I have been using $*recently, but don't ask me why. I don't know why, because I don't know why $@even exists, except as an almost exact synonym for $*.

$*最近一直在用,但不要问我为什么。我不知道为什么,因为我什至不知道为什么$@会存在,除了作为$*.

Is there any practical difference?

有什么实际区别吗?

(I personally tend to use Bash, but remain agnostic regarding the choice of shell. My question is not specific to Bash as far as I know.)

(我个人倾向于使用 Bash,但对 shell 的选择保持不可知论。据我所知,我的问题不是针对 Bash 的。)

回答by FatalError

Unquoted, there is no difference -- they're expanded to all the arguments and they're split accordingly. The difference comes when quoting. "$@"expands to properly quoted arguments and "$*"makes all arguments into a single argument. Take this for example:

不加引号,没有区别——它们被扩展到所有参数,并相应地拆分。区别在于引用时。"$@"扩展为正确引用的参数"$*"并使所有参数成为单个参数。以这个为例:

#!/bin/bash

function print_args_at {
    printf "%s\n" "$@"
}

function print_args_star {
    printf "%s\n" "$*"
}

print_args_at "one" "two three" "four"
print_args_star "one" "two three" "four"

Then:

然后:

$ ./printf.sh 

one
two three
four

one two three four

回答by William Pursell

Consider:

考虑:

foo() { mv "$@"; } 
bar() { mv "$*"; }
foo a b
bar a b

The call to foo will attempt to mv file a to b. The call to bar will fail since it calls mv with only one argument.

对 foo 的调用将尝试将文件 a 转为 b。对 bar 的调用将失败,因为它只用一个参数调用 mv。

回答by glenn Hymanman

Note also that "$@"is magic onlywhen there's nothing else in the quotes. These are identical:

另请注意,只有当引号中没有其他内容时,这才"$@"是魔术。这些是相同的:

set -- a "b c" d
some_func "foo $*"  
some_func "foo $@"

In both cases, some_func receives one argument.

在这两种情况下, some_func 都接收一个参数。