您的位置:首页 > 运维架构 > Shell

Linux Bash Shell $*和$@的区别

2016-01-11 20:56 375 查看
在 Linux Bash Shell 中,$* 和 $@ 都表示参数列表中的所有参数,它们在具体使用中会有哪些不同呢?这里我们可以写一个 Shell 脚本做实验:

#!/bin/bash

# This script is to verify the difference between $* and $@

echo Dollar Star is $*
echo "Dollar Star in double quotes is $*"

echo Dollar At is $@
echo "Dollar At in double quotes is $@"

echo
echo "Looping through Dollar Star"
for i in $*
do
echo "parameter is $i"
done
echo
echo "Looping through Dollar Star with double quotes"
for i in "$*"
do
echo "Parameter is $i"
done

echo
echo "Looping through Dollar At"
for i in $@
do
echo "Parameter is $i"
done
echo
echo "Looping through Dollar At with double quotes"
for i in "$@"
do
echo "Parameter is $i"
done


文件保存为 star.sh,并给予可执行权限:

# chmod 755 star.sh


然后我们执行以下命令:

# ./star.sh 1 "2  3 " 4   5


结果如下:

Dollar Star is 1 2 3 4 5
Dollar Star in double quotes is 1 2  3  4 5
Dollar At is 1 2 3 4 5
Dollar At in double quotes is 1 2  3  4 5

Looping through Dollar Star
parameter is 1
parameter is 2
parameter is 3
parameter is 4
parameter is 5

Looping through Dollar Star with double quotes
Parameter is 1 2  3  4 5

Looping through Dollar At
Parameter is 1
Parameter is 2
Parameter is 3
Parameter is 4
Parameter is 5

Looping through Dollar At with double quotes
Parameter is 1
Parameter is 2  3
Parameter is 4
Parameter is 5


由以上输出结果可以得出两者的相同点如下:

1、直接输出不保留空格

2、带双引号输出会保留带引号的空格

3、不带双引号循环遍历的输出结果一样:每个字符串单独输出

不同点如下:

1、带双引号遍历$*相当于带双引号输出$*

2、带双引号遍历$@分别输出每个参数,带双引号的参数保留空格输出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: