Shell中的特殊变量($0、$#、$*、$@、$$、$!、$?、$1~$n)
在Shell中,$*和$@分别代表如下含义:$0 : 脚本自身的名称
$# : 位置参数的个数
$* : 所有的位置参数都会被看成一个字符串
$@ : 每个位置参数会被看做一个独立的字符串
$$ :当前进程的PID
$! : Shell最后运行的后台进程的PID
$?: 返回上一次命令是否执行成功;0表示执行成功,非0表示执行失败
$1~$n : 添加到Shell的各参数值。$1是第1参数、$2是第2参数…。
示例:
#!/bin/bash
echo "The name of this shell script is: $0"
echo "First param is: $1"
echo "Second param is: $2"
echo "Third param is: $3"
echo "The total number of param is: $#"
for i in "$*";
do
echo $i
done
for n in "$@";
do
echo $n
done
echo "The PID of current process: $$"
echo $!
测试结果:
# bash var_1.sh a b c
The name of this shell script is: var_1.sh
First param is: a
Second param is: b
Third param is: c
The total number of param is: 3
a b c
a
b
c
The PID of current process: 20022
# echo $?
0
$*和$@的区别:
从测试结果中可以看出 $*是将所有的位置参数当做一个字符串输入;而$@则是将每个位置参数当做一个独立的字符串输出了。
页:
[1]