首页 > 应用开发 > IT综合 > Shell 参数的读取和处理
Shell脚本经常需要传入一些参数。下面的脚本可以作为一个通用模块,在写shell时用来
1. 指定参数的类型
2.
允许用户灵活指定参数顺序,或者省掉某几个参数
3. 通过shift命令,将参数传给指定的变量
注意
1. getopt a:b:c $*
$*和c之间有空格(必须)
2. basename用处
3.
shift用法
$ cat getopt1
#!/bin/sh
set -- `getopt a:b:c: $*`
getopt_rc=$?
if [ "$getopt_rc" -ne "0" ]; then
pgm=`basename $0`
echo
"$pgm $getopt_rc Process failed during getopt attempt - illegal
parameters"
exit 10
fi
while [ $# -gt 0 ]; do
case $1
in
-a)
shift
p1=$1
echo "-a is
$p1"
shift
;;
-b)
shift
p2=$1
echo "-b is
$p2"
shift
;;
-c)
shift
p3=$1
echo "-c is
$p3"
shift
;;
--)
shift
echo "case --"
#一般shell中直接break结束循环,没有该echo
break
esac
done
执行结果如下:
$ ./getopt1 -a AA -b BB -c CC
-a is AA
-b is BB
-c is
CC
-- case
$ ./getopt1 -b BB
-b is BB
-- case
$
./getopt1 -b BB -d DD
getopt: invalid option -- d
-b is BB
--
case
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/207/viewspace-905998/ ,如需转载,请注明出处,否则将追究法律责任。