getopts
getopts optstring name [arg]
每次调用时,getopts都会将下一个变量放在shell变量$name 中,如果不存在则初始化名称,放在shell变量 OPTIND 里的索引的参数将会被处理。 当一个选项需要一个参数时,getopts将该参数放入shell变量OPTARG中。
getopts source code: http://ftp.gnu.org/gnu/bash/
1. getopts demo
#!/bin/bash
#> File Name: get_opt.sh
#> Author:
#> Mail:
# ************************************************************************/
function usage()
{
echo "usage:
-w width
-h height
-f format
-F filename
example ./get_opt.sh -w 1920 -h 1080 -f NV12 -F ./test.NV12
"
}
function parse_args()
{
while getopts "h:w:f:F:H" OPTION; do
case $OPTION in
h)
height="${OPTARG}"
;;
w)
width="${OPTARG}"
;;
f)
format="${OPTARG}"
;;
F)
file_name="${OPTARG}"
;;
H)
usage
exit -1
;;
?)
usage
exit -1
;;
esac
done
return 0
}
######################## main ###########################
parse_args $@
echo height: $height
echo width: $width
echo format: $format
echo file name: $file_name
执行结果:
./get_opt.sh -w 1920 -h 1080 -f nv12 -F ./test.nv12
./get_opt.sh -H
while getopts "h:w:f:F:H" OPTION; do
在getopt 参数选项中有:跟无:的区别:
在参数选项后有 ”:“ 参数后需要参数值
在参数选项后没有":", 参数选项不需要跟数值