如果命令行程序的选项全部为短选项可以通过getopts来解析命令行选项。如下程序test.sh。
#! /bin/bash
printUsage(){
echo "usage: test.sh -i <filename> -o <filename> [args...]"
exit -1
}
if [ $# -eq 0 ];then
printUsage
fi
while getopts :hi:o: opts;do
case "$opts" in
i)
inputfile=$OPTARG
if [ ! -f $inputfile ];then
echo "The input file $inputfile doesn't exist!"
exit -1
fi
;;
o)
outputfile=$OPTARG
;;
h)
printUsage
;;
:)
echo "$0 must supply an argument to option -$OPTARG!"
printUsage
;;
?)
echo "invalid option -$OPTARG ignored!"
printUsage
;;
esac
done
if [ -z "$outputfile" ];then
printUsage
exit -1
fi
echo "inputfile:$inputfile
outputfile:$outputfile"
shift $(($OPTIND-1));
if [ $# -gt 0 ];then
echo "other arguments:$@";
fi
简单测试: