开启密码H1N6Yll2
shift命令
shift n 每次将参数位置向左偏移n
#!/bin/bash
#opt2
usage()
{
echo “usage:`basename $0` filename”
}
totalline=0
if [ $# -lt 2 ];then
usage
fi
while [$# -ne 0]
do
line=`cat $1|wc -l`
echo “$1 : ${line}”
totalline=$[$totalline+$line]
shift # $# -1
done
echo “—–”
echo “total:${totalline}”
[test@szbirdora 1]$ sh opt2.sh myfile df.out
myfile : 10
df.out : 4
—–
total:14
8.getopts命令
获得多个命令行参数
getopts ahfvc OPTION –从ahfvc一个一个读出赋值给OPTION.如果参数带有:则把变量赋值给:前的参数–:只能放在末尾。
该命令可以做获得命令的参数
#!/bin/bash
#optgets
ALL=false
HELP=false
FILE=false
while getopts ahf OPTION
do
case $OPTION in
a)
ALL=true
echo “ALL is $ALL”
;;
h)
HELP=true
echo “HELP is $HELP”
;;
f)
FILE=true
echo “FILE is $FILE”
;;
?)
echo “`basename $0` -[a h f] file”
;;
esac
done
[test@szbirdora 1]$ sh optgets.sh -a -h -m
ALL is true
HELP is true
optgets.sh: illegal option — m
optgets.sh -[a h f] file
getopts表达式:
while getopts p1p2p3… var do
case var in
..)
….
esac
done
如果在参数后面还需要跟自己的参数,则需要在参数后加:
如果在参数前面加:表示不想将错误输出
getopts函数自带两个跟踪参数的变量:optind,optarg
optind初始值为1,在optgets处理完一次命令行参数后加1
optarg包含合法参数的值,即带:的参数后跟的参数值
至此,基础部分先告一段落,接下来我会继续发行shell的高级编程部分。
谢谢!