shell中$*,$@,$# 的区别

18 篇文章 0 订阅

$@ 和  $* 只在被双引号包起来的时候才会有差异


双引号括起来的情况:
$*将所有的参数认为是一个字段
$@以 默认为空格 来划分字段,如果空格在“”里面,不划分

没有括起来的情况是$@和$*一样的,见到 空格 就划分字段

$#是 程序的 参数个数(不包括$0)

$? 获取上一次命令执行的返回值,一般 执行 成功 返回0。

$0 $1 $2 以此类推,取命令行参数,如 test.sh a b c ,则 $0 是 test,$1是 a, $2是b,$3是c。


一个小例子 ,仅供参考

test.sh内容如下:

#!/bin/bash

index=1
echo "Listing args with\"\$*\":"
for arg in "$*"

do
echo "Arg #$index=$arg"
let "index+=1"
done

echo "all parameter is one word"
echo

index=1
echo "Listing args with \"\$@\":"
for arg in "$@"
do
echo "Arg #$index=$arg"
let "index+=1"
done

echo "all parameter is all kinds of different words"
echo

index=1
echo "Listing args with \$* "
for arg in $*
do
echo "Arg #$index=$arg"
let "index+=1"
done
echo "all parameter is all kinds of different words"

echo

index=1
echo "Listing args with \$r@ "
for arg in $@
do
echo "Arg #$index=$arg"
let "index+=1"
done

echo

echo "all parameter is all kinds of different words"


运行结果如下
$ ./test.sh 1 2 3 "4 5"
Listing args with"$*":
Arg #1=1 2 3 4 5
all parameter is one word

Listing args with "$@":
Arg #1=1
Arg #2=2
Arg #3=3
Arg #4=4 5
all parameter is all kinds of different words

Listing args with $*
Arg #1=1
Arg #2=2
Arg #3=3
Arg #4=4
Arg #5=5
all parameter is all kinds of different words


Listing args with $r@
Arg #1=1
Arg #2=2
Arg #3=3
Arg #4=4
Arg #5=5
all parameter is all kinds of different words

the number of all parameter is 4




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值