脚本参数($0,$1...)
/path/to/scriptname opt1 opt2 opt3
- $0表示第一部分,即"/path/to/scriptname"
- $1表示第一个参数,即"opt1"
- $2表示第二个参数,即"opt2"
- $3表示第三个参数,即"opt3"
- $#表示参数的个数
- $@表示参数整体,即"opt1 opt2 opt3"
来个例子
#!/bin/bash
echo "The script name is ==> ${0}"
echo "Total parameter number is ==> $#"
# 参数不足2个时退出
[ "$#" -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}"
通过这条命令执行:./how_paras.sh a b c
结果:
The script name is ==> ./how_paras.sh
Total parameter number is ==> 3
Your whole parameter is ==> 'a b c'
The 1st parameter ==> a
The 2nd parameter ==> b
使用shift进行参数偏移
直接来看例子:
#!/bin/bash
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift # 偏移一次
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift 3 # 偏移三次
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
通过这条命令执行:./shift_paras.sh a b c d
结果:
Total parameter number is ==> 4
Your whole parameter is ==> 'a b c d'
Total parameter number is ==> 3
Your whole parameter is ==> 'b c d'
Total parameter number is ==> 0
Your whole parameter is ==> ''
网友评论