Shell脚本传参数方法总结
一、接收固定长度的参数
[root@svn shell_example]# cat params.sh
#!/bin/bash
#传参测试脚本
echo "my name is `basename $0` -i was called as $0"
echo "my first parameter is : $1"
echo "my second parameter is : $2"
空参数执行
[root@svn shell_example]# sh params.sh
my name is params.sh -i was called as params.sh
my first parameter is :
my second parameter is :
传递2个参数执行
[root@svn shell_example]# sh params.sh one two
my name is params.sh -i was called as params.sh
my first parameter is : one
my second parameter is : two
二、那如果还有参数怎么办呢?还要一个个加上来吗?答案是否定的
以下用法应该不陌生,就是直接执行脚本本身,没有附带任何参数,那么脚本讲抛出帮助信息.即怎么使用此脚本.见红字部分
[root@svn shell_example]# sh params_v2.sh
my name is params_v2.sh -i was called as params_v2.sh
i was called with 0 parameters.
usage: params_v2.sh first second
you provided 0 parameters,but 2 are required.
代码如下
[root@svn shell_example]# cat params_v2.sh
#!/bin/bash
# 这是个测试脚本传参的测试例子
echo "my name is `basename $0` -i was called as $0"
echo "i was called with $# parameters."
if [ "$#" -eq "2" ];then
echo "my first parameter is $1"
echo "my second parameter is $2"
else
echo "usage: `basename $0` first second"
echo "you provided $# parameters,but 2 are required."
fi
详细的执行过程如下
不传参数执行
[root@svn shell_example]# sh params_v2.sh
my name is params_v2.sh -i was called as params_v2.sh
i was called with 0 parameters.
usage: params_v2.sh first second
you provided 0 parameters,but 2 are required.
传递3个参数执行
[root@svn shell_example]# sh params_v2.sh one two three
my name is params_v2.sh -i was called as params_v2.sh
i was called with 3 parameters.
usage: params_v2.sh first second
you provided 3 parameters,but 2 are required.
传递2个参数执行
[root@svn shell_example]# sh params_v2.sh one two
my name is params_v2.sh -i was called as params_v2.sh
i was called with 2 parameters.
my first parameter is one
my second parameter is two
问题来了,要是后期还要加参数怎么办呢?或者我也不确定到底会传几个参数.
解决方法如下,详细执行结果如下
[root@svn shell_example]# cat manyparams.sh
#!/bin/bash
#这是个测试脚本传n个参数的例子
echo "我的名字是 `basename $0` - 我是调用自 $0"
echo "我有 $# 参数"
count=1
while [ "$#" -ge "1" ];do
echo "参数序号为 $count 是 $1"
let count=count+1
shift
done
一个参数执行
[root@svn shell_example]# sh manyparams.sh one
我的名字是 manyparams.sh - 我是调用自 manyparams.sh
我有 1 参数
参数序号为 1 是 one
5个参数执行
[root@svn shell_example]# sh manyparams.sh one two three four five
我的名字是 manyparams.sh - 我是调用自 manyparams.sh
我有 5 参数
参数序号为 1 是 one
参数序号为 2 是 two
参数序号为 3 是 three
参数序号为 4 是 four
参数序号为 5 是 five