sh 标准的bash模板

Posted

tags:

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

#!/usr/bin/env bash
usage() {
    cat <<EOF
NAME:
    $(basename $0)

DESCRIPTION:
    TODO: describe me

SYNOPSIS:
    $(basename $0)
    --required-opt <value>
    [--optional-opt <value>]

OPTIONS:
    --required-opt (string)
        TODO: describe me

    --optional-opt (string)
        TODO: describe me

EOF
    exit
}

#-------------------------------------------------------------------------------
# Defaults
#-------------------------------------------------------------------------------
: ${OPTIONAL_OPT:="foo"}

#-------------------------------------------------------------------------------
# Parse cli options
#-------------------------------------------------------------------------------
while [[ $# > 0 ]]
do
    key="$1"

    case $key in
        help)
            usage
            ;;
        --required-opt)
            CLI_REQUIRED_OPT="$2"
            shift
            ;;
        --optional-opt)
            CLI_OPTIONAL_OPT="$2"
            shift
            ;;
        *)
            # unknown option
            ;;
    esac
    shift # past argument or value
done

#-------------------------------------------------------------------------------
# Set options, falling back to env vars if option values are not provided on
# the cli
#-------------------------------------------------------------------------------
REQUIRED_OPT=${CLI_REQUIRED_OPT:-$REQUIRED_OPT}
OPTIONAL_OPT=${CLI_OPTIONAL_OPT:-$OPTIONAL_OPT}

#-------------------------------------------------------------------------------
# Validate options
#-------------------------------------------------------------------------------
: ${REQUIRED_OPT:?"ERROR: Required option not provided."}

#-------------------------------------------------------------------------------
# Functions
#-------------------------------------------------------------------------------

#-------------------------------------------------------------------------------
# Body
#-------------------------------------------------------------------------------

以上是关于sh 标准的bash模板的主要内容,如果未能解决你的问题,请参考以下文章

sh bash的命令行选项解析器模板

sh 模板与bash脚本的一些便利设置。

sh Bash脚本模板

sh bash子命令模板

sh Bash模板。可能适用于中等或更多涉及的脚本。

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