在bash脚本$ @ $和*之间的区别 [英] Difference between $@ and $* in bash scripting

查看:158
本文介绍了在bash脚本$ @ $和*之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在bash新我学习它,我有一个关于使用 $ @ S * 。

I'm new in bash and I'm learning it, and I have a doubt about the real difference between the use of $@ and S*.

我在这里红猛砸特殊参数

据我所知,这两个扩展到位置参数,但双引号内的差异发生。
顺便说一句$ @=$ 1$ 2...$ N能比不同的S *= $ 1 $ 2 ... $ N。

I understand that both expand to the positional parameters, but the difference occurs within double quotes. By the way "$@" = "$1" "$2"..."$n" could be different than "S*" = "$1$2...$n".

我尝试用简单的脚本来理解它:

I try to understand it with a simple script:

if [ $# -gt 0 ]; then
       echo "Your command line contains $# arguments" 
else
       echo "Your command line contains no arguments"
       exit  fi

echo "Params are: "
echo $@  
echo $* 
echo "$@"    
echo "$*"

如果我在这样的终端执行我的剧本〜/ my_script PAR1 par2的PAR3

if I execute my script in the terminal like this ~./my_script par1 par2 par3

结果总是相同的:

Params are:
par1 par2 par3
par1 par2 par3
par1 par2 par3
par1 par2 par3

也许我不明白真正使用这两个特殊变量,并且如果我的例子是正确与否。我想也搞清楚了这一点与一个很好的例子。

Maybe I don't understand the real use of both special variables and If my example is correct or not. I'd like to figure out this point also with a good example.

推荐答案

的http:/ /tldp.org/LDP/abs/html/refcards.html :

$ *所有的位置参数(如一个单词)*

"$*" All the positional parameters (as a single word) *

$ @所有的位置参数(作为单独的字符串)

"$@" All the positional parameters (as separate strings)

这code说明它:给出用空格分隔项的字符串, $ @ 认为每一个字作为一个新的项目,而 $ * 认为它们放在一起相同的参数。

This code shows it: given a string with items separated by spaces, $@ considers every word as a new item, while $* considers them all together the same parameter.

echo "Params for: \$@"
for item in "${@}"
do
        echo $item --
done

echo "Params for : \$*"
for item in "${*}"
do
        echo $item --
done

测试:

$ ./a par1 par2 par3
Your command line contains 3 arguments
Params for: $@
par1 --
par2 --
par3 --
Params for : $*
par1 par2 par3 --

这篇关于在bash脚本$ @ $和*之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆