:特殊变量列表
- $0 当前脚本的文件名
- $n 传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。
- $# 传递给脚本或函数的参数个数
- $* 传递给脚本或函数的所有参数。
- $@ 传递给脚本或函数的所有参数。被双引号(” “)包含时,与 $* 稍有不同
- $? 上个命令的退出状态,或函数的返回值。
- $$ 当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。
脚本:
#!/usr/bin/env sh
echo "pid" " " "\$\$ -> $$"
echo "filename" " " "\$0 -> $0"
echo "param1" " " "\$1 -> $1"
echo "param2" " " "\$2 -> $2"
echo "allparams" " " "\$* -> $*"
echo "allparams" " " "\$@ -> $*"
echo "totalparams" " " "\$# -> $#"
运行命令:
./test p1 p2 p3
运行结果:
pid $$ -> 717
filename $0 -> ./test.sh
param1 $1 -> p1
param2 $2 -> p2
allparams $* -> p1 p2 p3
allparams $@ -> p1 p2 p3
totalparams $# -> 3
$* $@区别
$* 和 $@ 都表示传递给函数或脚本的所有参数,不被双引号(” “)包含时,都以”$1” “$2” … “$n” 的形式输出所有参数。
但是当它们被双引号(” “)包含时,”$*” 会将所有的参数作为一个整体,以”$1 $2 … $n”的形式输出所有参数;”$@” 会将各个参数分开,以”$1″ “$2” … “$n” 的形式输出所有参数。
#!/usr/bin/env sh
echo "\$*=" $*
echo "\"\$*\"=" "$*"
echo "\$@=" $@
echo "\"\$@\"=" "$@"
echo "print each param from \$*"
for var in $*
do
echo "$var"
done
echo "print each param from \$@"
for var in $@
do
echo "$var"
done
echo "print each param from \"\$*\""
for var in "$*"
do
echo "$var"
done
echo "print each param from \"\$@\""
for var in "$@"
do
echo "$var"
done
./test a b c d
$*= a b c d
"$*"= a b c d
$@= a b c d
"$@"= a b c d
print each param from $*
a
b
c
d
print each param from $@
a
b
c
d
print each param from "$*"
a b c d
print each param from "$@"
a
b
c
d