Linux之向脚本传参数
之前我们向脚本传递参数可以通过$1,$2等特殊变量。很方便,但是有些限制,就是不能超过9个参数。通过使用shift和getopts命令,我们可以十分方便的向脚本传递参数。
一、shift
通过使用shift,我们将参数选项从左向右移。
看下面这个例子:
#!/bin/sh
# shift_sample
if [ $# -lt 1 ]
echo "too few params"
exit 1
fi
while [ $# -ne 0 ]
do
echo $1
shift
done
在命令行下输入:
#:shift_sample one two three
输出结果如下:
one
two
three
二、getopts
如果你的脚本命令后有一些选项开关,比如-i,-c等等,这个时候使用shift来挨个查看比较麻烦。而用getopts则比较方便。
getopts使用格式如下:
getopts format_string variable
还是看一个例子:
#!/bin/sh
#getopts_sample
if [ $# -lt 1 ]
echo "too few params"
exit 1
fi
while getopts hv OPTION
do
case $OPTION in
h)echo "this is help information"
;;
v)echo "the version is 1.0.0"
;;
done
这段脚本允许两个参数选项,分别是-h,-v,使用的时候可以分开来写,像-h -v,也可以连在一起,像-hv。
在命令行下输入:
#:getopts_sample -h -v
输出:
this is help information
the version is 1.0.0
如果选项需要输入值,则在参数选项后面加上:,比如:
getopts hvc: OPTION
这个时候调用该脚本,则使用如下格式:
getopts_sample -h -v -c HELLO
脚本在读到-c的时候,会把它的值存储在$OPTARG变量中。