Linux shell中使用 getopts 处理输入参数

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 参数选项中有:跟无:的区别:
在参数选项后有 ”:“ 参数后需要参数值
在参数选项后没有":", 参数选项不需要跟数值
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值