特殊变量列表
变量 | 含义 |
---|---|
$0 | 当前脚本的文件名,包含路径 |
$n | 传递给脚本或者函数的参数. n 是一个数字,表示第几个参数。例如,第一个参数是 1,第二个参数是 2 |
$# | 传递给脚本或者函数的参数的个数 |
$* | 传递给脚本或函数的所有参数 |
$@ | 传递给脚本或函数的所有参数 |
$? | 上个命令的退出状态,或函数的返回值 |
$! | 上一个执行命令的PID |
$_ | 在此之前执行的命令或者脚本的最后一个参数 |
实例
$ cat shell.sh
#!/bin/bash
echo "the file name is: $0"
echo "the 1st argument is: $1"
echo "the 2nd argument is: $2"
echo "number of argument is: $#"
echo "state of last command is: $?"
echo "PID of last command is: $!"
echo "PID of current command is: $$"
echo "the last argument is: $_"
执行结果:
$ ./shell.sh shell test
the file name is: ./shell.sh //即会带上执行脚本时用的路径.
the 1st argument is: shell
the 2nd argument is: test
number of argument is: 2
state of last command is: 0
PID of last command is:
PID of current command is: 31437
the last argument is: PID of current command is: 31437
注意区别$*与$@
$*与$@都表示的是传递给脚本或函数的所有参数。
不被双引号(” “)包含时,都以”$1” “$2” … “$n” 的形式输出所有参数。
但是当它们被双引号(” “)包含时,”$*” 会将所有的参数作为一个整体,以”$1 $2 … $n”的形式输出所有参数;”$@” 会将各个参数分开,以”$1” “$2” … “$n” 的形式输出所有参数。
cat ./shell.sh
#!/bin/bash
echo "all the arguments are (result from \$*): $*"
echo "all the arguments are (result from \$@): $@"
echo "all the arguments are (result from \"\$*\"): "$*""
echo "all the arguments are (result from \"\$@\"): "$@""
echo "each result from \$*:"
for i in $*
do
echo "$i"
done
echo "each result from \$@:"
for i in $@
do
echo "$i"
done
echo "each result from \"\$*\":"
for i in "$*"
do
echo "$i"
done
echo "each result from \"\$@\":"
for i in "$@"
do
echo "$i"
done
执行结果:
$ ./shell.sh shell test
all the arguments are (result from $*): shell test
all the arguments are (result from $@): shell test
all the arguments are (result from "$*"): shell test
all the arguments are (result from "$@"): shell test
each result from $*:
shell
test
each result from $@:
shell
test
each result from "$*":
shell test
each result from "$@":
shell
关于$?
获取上一个命令的退出状态。所谓退出状态,就是上一个命令执行后的返回结果。
退出状态是一个数字,一般情况下,大部分命令执行成功会返回 0,失败返回 1。不过,也有一些命令返回其他值,表示不同类型的错误。
0 表示运行成功
2 表示权限拒绝
1~125 表示运行失败, 脚本命令/系统命令/参数传递错误
126 找到了该命令, 但是取法执行
127 未找到要运行的命令
128 命令被系统强制结束