在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n
。n 代表一个数字,1 为执行脚本的第一个参数,2 为执行脚本的第二个参数,以此类推……。其中 $0
为执行的文件名。
注意
:$10 不能获取第十个参数,获取第十个参数需要 ${10}。当 n>=10 时,需要使用 ${n} 来获取参数。
参数 | 说明 |
---|---|
$# | 传递到脚本的参数个数 |
$* | 显示所有向脚本传递的参数 |
$$ | 脚本运行的当前进程ID号 |
$@ | 与$*相同,但是使用时加引号,并在引号中返回每个参数 |
$? | 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。 |
#!/bin/bash
echo "The script name is $0"
echo "The first parameter is $1"
echo "The second parameter is $2"
echo "The sum of all parameters is $#"
echo "The total parameters are $*"
echo "Current the script process IDis $$"
echo "The total parameters are $@"
echo "The exit status of the last command is $?"
# sh test.sh 1 2 3
The script name is test.sh
The first parameter is 1
The second parameter is 2
The sum of all parameters is 3
The total parameters are 1 2 3
Current the script process IDis 9504
The total parameters are 1 2 3
The exit status of the last command is 0
网友评论