本文编辑自: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