shell脚本文件参数

本文编辑自:http://hi.baidu.com/abcserver/blog/item/5efe716331ebfb6e0d33fab2.html
当我们我们向 脚本文件传递参数 可以通过 $1,$2 等特殊变量。很方便,但是有些限制,就是不能超过9个参数。通过使用 shift ,我们可以向脚本文件传递更多的参数,通过 getopts 我们能更方便地提取参数。
一、shift
通过使用 shift ,我们将 shell脚本文件 的参数起点从左向右移。
在shift命令中可以给一个参数,以表示对shell脚本文件的传入参数启动从左向右移动多少。不给参数的话,表示移动一位。
实例1
test.sh文件
#!/bin/sh
# shift_sample
if [ $# -lt 1 ];then
echo "too few params"
exit 1
fi

while [ $# -ne 0 ]
do
echo $1
shift
done
在命令行下输入:
sh test.sh a b c
输出结果如下:
a
b
c
注意:“ $#”表示shell脚本文件传入参数的个数。
二、getopts
如果你的脚本命令后有一些选项开关,比如 -i -c 等等,这个时候使用shift来挨个查看比较麻烦。而用getopts则比较方便。getopts使用格式如下:
getopts format_string variable
实例2
test.sh文件
#getopts_sample
if [ $# -lt 1 ];then
echo "too few params"
exit 1
fi

while getopts hv OPTION
do
case $OPTION in
h) echo "this is help information"
shift
;;
v) echo "the version is 1.0.0"
shift
;;
--)echo the option is end
shift
;;
esac
done
echo $1
这段脚本允许两个参数选项,分别是-h,-v,使用的时候可以分开来写,像-h -v,也可以连在一起,像-hv
运行命令“ sh test.sh -h -v Hello ”或 sh test.sh -hv Hello ,你将得到如下结果:
this is help information
the version is 1.0.0
hello
如果选项需要输入值,则在参数选项后面加上“ : ”,比如:getopts hvc: OPTION脚本在读到-c的时候,会把它的参数值存储在$OPTARG变量中。
实例3
test.sh文件
#!/bin/sh
#getopts_sample
if [ $# -lt 1 ];then
echo "too few params"
exit 1
fi

while getopts hv:t: OPTION
do
case $OPTION in
h) echo "this is option h"
shift 1
;;
v) echo "this is option v.And the var is " $OPTARG
shift 2
;;
t) echo "this is option t.And the var is " $OPTARG
shift 2
;;
esac
done
echo $1
运行命令“ sh test.sh -h -v vv -t tt hello ”将得到如下结果:
this is option h
this is option v.And the var is vv
this is option t.And the var is tt
hello

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值