特殊变量列表
变量 | 含义 |
---|---|
$0 | 当前脚本的文件名 |
$n | 传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。 |
$# | 传递给脚本或函数的参数个数。 |
$* | 传递给脚本或函数的所有参数。 |
$@ | 传递给脚本或函数的所有参数。被双引号(” “)包含时,与 $* 稍有不同,下面将会讲到。 |
$? | 上个命令的退出状态,或函数的返回值。 |
$$ | 当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。 |
命令行参数
运行脚本时传递给脚本的参数称为命令行参数。命令行参数用 $n 表示,例如,$1 表示第一个参数,$2 表示第二个参数,依次类推。请看下面的脚本:
# cat argc.sh #!/bin/bash echo "File Name: $0" echo "First Parameter : $1" echo "First Parameter : $2" echo "Quoted Values: $@" echo "Quoted Values: $*" echo "Total Number of Parameters : $#"
运行结果:
# sh argc.sh arg1 arg2 arg3 File Name: argc.sh First Parameter : arg1 First Parameter : arg2 Quoted Values: arg1 arg2 arg3 Quoted Values: arg1 arg2 arg3 Total Number of Parameters : 3
需要注意的是$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。示例如下:
# cat 10argc.sh #!/bin/bash funWithParam(){ echo "The value of the first parameter is $1 !" echo "The value of the second parameter is $2 !" echo "The value of the tenth parameter is $10 !" echo "The value of the tenth parameter is ${10} !" echo "The value of the eleventh parameter is ${11} !" echo "The amount of the parameters is $# !" # 参数个数 echo "The string of the parameters is $* !" # 传递给函数的所有参数 } funWithParam 1 2 3 4 5 6 7 8 9 34 73
执行结果如下:
# sh 10argc.sh The value of the first parameter is 1 ! The value of the second parameter is 2 ! The value of the tenth parameter is 10 ! The value of the tenth parameter is 34 ! The value of the eleventh parameter is 73 ! The amount of the parameters is 11 ! The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !
$* 和 $@ 的区别
$* 和 $@ 都表示传递给函数或脚本的所有参数,不被双引号(” “)包含时,都以”$1” “$2” … “$n” 的形式输出所有参数。但是当它们被双引号(” “)包含时,”$*” 会将所有的参数作为一个整体,以”$1 $2 … $n”的形式输出所有参数;”$@” 会将各个参数分开,以”$1″ “$2” … “$n” 的形式输出所有参数。
下面的例子可以清楚的看到 $* 和 $@ 的区别:
# cat param.sh #!/bin/bash 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 \"\$*\"" echo "print each param from '$*'" for var in "$*" do echo "$var" done #echo "print each param from \"\$@\"" echo "print each param from '$@'" for var in "$@" do echo "$var" done
脚本执行结果如下:
# sh param.sh 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' a b c d print each param from 'a b c d' a b c d
退出状态与返回值
$? 可以获取上一个命令的退出状态。所谓退出状态,就是上一个命令执行后的返回结果。退出状态是一个数字,一般情况下,大部分命令执行成功会返回 0,失败返回 1。不过,也有一些命令返回其他值,表示不同类型的错误。下面例子中,命令成功执行:
# sh argc.sh argc1 argc2 File Name: argc.sh First Parameter : argc1 First Parameter : argc2 Quoted Values: argc1 argc2 Quoted Values: argc1 argc2 Total Number of Parameters : 2 # echo $? 0
$? 也可以表示函数的返回值,返回值的示例如下:
# cat return.sh #/bin/bash function fSum() { echo $1,$2; return $(($1+$2)); } fSum 5 7; total=$(fSum 3 2); echo $total,$?;
脚本执行的结果如下:
# sh return.sh 5,7 3,2,5
注:需要注意的是无法使用aa=$?这样的用法调用返回值,使用echo $aa输出会是空。