9.Scripts
9.3.3 Shell script的默认变数($0, $1...)变量含义
$0当前脚本的文件名。
$n(n≥1)传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是 $1,第二个参数是 $2。
$#传递给脚本或函数的参数个数。
$*传递给脚本或函数的所有参数。
$@传递给脚本或函数的所有参数。
$?上个命令的退出状态,或函数的返回值。
$$当前 Shell 进程 ID。对于 Shell 脚本,就是这些脚本所在的进程 ID。
注:
n$@ :代表『 "$1" "$2" "$3" "$4" 』之意,每个变量是独立的(用双引号括起来);
n$* :代表『 "$1c$2c$3c$4" 』,其中 c 为分隔字符,默认为空格键,所以本例中代表『 "$1 $2 $3 $4" 』之意。
1.实例
[root@localhost tmp]# vim 1.sh
#!/bin/bash
echo "The script name is ==> ${0}"
echo "Total parameter number is ==> $#"
[ "$#" -lt 2 ] && echo "The number of parameter is less than 2. Stop here." && exit 0
echo "Your whole parameter is ==> '$@'"
echo "The 1st parameter ==> ${1}"
echo "The 2nd parameter ==> ${2}"
[root@localhost tmp]# sh 1.sh a b c d
The script name is ==> 1.sh
Total parameter number is ==> 4
Your whole parameter is ==> 'a b c d'
The 1st parameter ==> a
The 2nd parameter ==> b
[root@localhost tmp]# ./1.sh a b c d
The script name is ==> ./1.sh
Total parameter number is ==> 4
Your whole parameter is ==> 'a b c d'
The 1st parameter ==> a
The 2nd parameter ==> b
2.shift:造成参数变量号码偏移
[root@localhost tmp]# vim shift.sh
#!/bin/bash
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift # 进行第一次『一个变量的 shift 』
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift 3 # 进行第二次『三个变量的 shift 』
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
[root@localhost tmp]# sh shift.sh a b c d e f g
Total parameter number is ==> 7
Your whole parameter is ==> 'a b c d e f g'
Total parameter number is ==> 6
Your whole parameter is ==> 'b c d e f g'
Total parameter number is ==> 3
Your whole parameter is ==> 'e f g'