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

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


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

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

$#是 程序的 参数个数(不包括$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




原文地址:https://www.cnblogs.com/liulaolaiu/p/11744772.html