sh 用于bash的模板getopts参数解析各种类型的参数。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sh 用于bash的模板getopts参数解析各种类型的参数。相关的知识,希望对你有一定的参考价值。

#!/bin/bash


### preallocate variables
required=
optional_hasarg=
got_opt_arg=false
optional_noarg=false
has_default="DEFAULT"

### initialize (clear) opt parsing variables
OPTIND=
OPTARG=
opt=

while getopts "ha:b:cd:" opt; do

    case "$opt" in
        h)
            echo "\
            usage:
            ------
            getoptsdemo [ -h ] -a REQ [ -b OPTHAS ] [ -c ] [ -d OPTDEF ]

            description:
            ------------
            This demonstrates parsing arguments with getopts

            optional arguments:
            -------------------
            -h          Print this help message and exit.
            -a REQ      Required opt that takes an argument.
            -b OPTHAS   Optional opt that takes an argument.
            -c          Optional opt that does not take an argument.
            -d OPTDEF   If given, sets value of has_default to OPTDEF.
                        Otherwise, the value of has_default defaults to
                        DEFAULT.

            "
            exit 0
            ;;
        a)
            required=${OPTARG}
            ;;
        b)
            optional_hasarg=${OPTARG}
            got_opt_arg=true
            ;;
        c)
            optional_noarg=true
            ;;
        d)
            has_default=${OPTARG}
            ;;
        ?)
            echo "Error: did not recognize option, ${OPTARG}."
            echo "Please try -h for help."
            exit 1
            ;;
    esac
done

if [[ "$required" == "" ]]; then
    echo "ERROR: Required option -a not set."
    echo "Please try -h for help."
    exit 1
fi

echo "required: $required"

if [[ "$got_opt_arg" == true ]]; then
    if [[ "$optional_hasarg" == "" ]]; then
        echo "-b option set but no argument given"
        echo "Please try -h for help."
        exit 1
    else
        echo "optional_hasarg: $optional_hasarg"
    fi
else
    echo "optional_hasarg not set"
fi

if [[ "$optional_noarg" == true ]]; then
    echo "optional_noarg set"
else
    echo "optional_noarg not set"
fi

echo "has_default: $has_default"

以上是关于sh 用于bash的模板getopts参数解析各种类型的参数。的主要内容,如果未能解决你的问题,请参考以下文章

使用 getopts (bash) 的多个选项参数

BASH:具有默认参数值的 getopts

在 Bash 中使用 getopts 检索单个选项的多个参数

在bash中使用getopts来获取可选的输入参数[重复]

Bash getopts,参数没有被传递给选项

sh 简单的bash shell脚本模板。有两个版本:1)简单的基于env var的选项,以及2)添加了命令行参数解析