当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - The difference between $* and [email protected]

问题描述:

Possible Duplicate:

What the difference between “[email protected]” and “$*” in bash?

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

I have been using $* recently, but don't ask me why. I don't know why, because I don't know why [email protected] 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.)

网友答案:

Unquoted, there is no difference -- they're expanded to all the arguments and they're split accordingly. The difference comes when quoting. "[email protected]" 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" "[email protected]"
}

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
网友答案:

Consider:

foo() { mv "[email protected]"; } 
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.

网友答案:

Note also that "[email protected]" is magic only when there's nothing else in the quotes. These are identical:

set -- a "b c" d
some_func "foo $*"  
some_func "foo [email protected]"

In both cases, some_func receives one argument.

分享给朋友:
您可能感兴趣的文章:
随机阅读: