shell编程之脚本参数$@,$*,$#,$$,$?的含义


#首先按顺序解释各个参数的含义

1.$0  表示脚本的文件名,

具体的路径信息和执行命令时的相对位置有关,例如

sakura@mi-OptiPlex-7050:~/sh$ sh args.sh
args.sh

sakura@mi-OptiPlex-7050:~$ sh sh/args.sh
sh/args.sh

2.$1,$2,... 表示具体的参数

3.$#  实际传入的参数的个数

4.$$  执行当前shell的进程pid

5.$? 上次执行的返回值,一般0表示成功.

#关于$@,$*,"$@","$*"的对比和及向java传参的对比

首先$@,$*都表示shell脚本接受的参数列表,不包括$0

其次"$@"中的""表示弱引用,即会对$后的变量进行替换.

通过以下shell脚本和java代码,可以清晰的看清楚四者的区别

echo '------------------$@-------------------'
echo $@
for arg in $@
do
echo -n "$arg,"
done
echo
java Test $@

echo '------------------$*-------------------'
echo $*
for arg in $*
do
echo -n "$arg,"
done
echo
java Test $*

echo '------------------"$@"-------------------'
echo "$@"
for arg in "$@"
do
echo -n "$arg,"
done
echo
java Test "$@"

echo '------------------"$*"-------------------'
echo "$*"
for arg in "$*"
do
echo -n "$arg,"
done
echo
java Test "$*"

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        System.out.println("java arg length: "+args.length);
        System.out.println("java arr: "+Arrays.toString(args));
    }
}

执行 sh test.sh 1 ab 3,输出如下

------------------$@-------------------
1 ab 3
1,ab,3,
java arg length: 3
java arr: [1, ab, 3]
------------------$*-------------------
1 ab 3
1,ab,3,
java arg length: 3
java arr: [1, ab, 3]
------------------"$@"-------------------
1 ab 3
1,ab,3,
java arg length: 3
java arr: [1, ab, 3]
------------------"$*"-------------------
1 ab 3
1 ab 3,
java arg length: 1
java arr: [1 ab 3]

执行sh test.sh 输入如下

------------------$@-------------------


java arg length: 0
java arr: []
------------------$*-------------------


java arg length: 0
java arr: []
------------------"$@"-------------------


java arg length: 0
java arr: []
------------------"$*"-------------------

,
java arg length: 1
java arr: []

结论

$*,$@一样,都是传递整个参数列表,但是当被""引用时,$@不变,为多个字符串,而$*为一个字符串,并且如果这个参数列表为空,则字符串为空字符串,而非不存在.