随笔-shell-解析脚本参数(getopt)

    # 用法:getopt [options] [--] optstring parameters
    # -o或--options选项后面接可接受的短选项,如ab:c::,表示可接受的短选项为-a -b -c,其中-a选项不接参数,-b选项后必须接参数,-c选项的参数为可选的
    # -l或--long选项后面接可接受的长选项,用逗号分开,冒号的意义同短选项。
    # -n 选项后接选项解析错误时提示的脚本名字
    # PS : 一般情况下 getopt 解析结果以 -- 结尾, 如果 optstring parameters 中含有参数不是以-或--开头,则会被放置在--后面
    # e.g: a -b --c ==> b c -- a

OPTION_SHORT=$(cat <<- _EOF_
    h:,
    d:,
    m:,
    p:,
    n:,
_EOF_
)

OPTION_LONG=$(cat <<- _EOF_
    save,
_EOF_
)

function util_div_string() {
    declare -a local tmp_arr
    local separator="$1"
    local string="$2"

    [[ -z "$separator" || -z "$string" ]] && return

    OLD_IFS="$IFS"
    IFS=$separator
    tmp_arr=($string)
    IFS="$OLD_IFS"

    echo "${tmp_arr[@]}"
}

function util_apply_optstring() {
    while [ $# -gt 0 ]; do
        case "$1" in
            -h)
                echo $usage_desc
                exit 0
                ;;
            -d)
                date_range="$2"
                shift 2
                ;;
            -m)
                module_list=($(util_div_string "|" "$2"))
                shift 2
                ;;
            -p)
                pkg_proto=($(util_div_string "|" "$2"))
                shift 2
                ;;
            --save|save)
                save_opt="save"
                echo "$save_opt"
                shift 1
                ;;
            -n)
                log_cnt_max=$2
                shift 2
                ;;
            --)
                shift
                # break
                ;;
            *)
                echo "无效选项: $1!"
                shift
                ;;
        esac
    done
}

function util_parse_optstring() {
    local PARAMETERS=""

    [[ $# -eq 0 ]] && return

    PARAMETERS=`getopt -o "${OPTION_SHORT}" -l "${OPTION_LONG}" -n 'mlog' -- "$@"`
    if [ $? != 0 ]; then
        echo "bad paramters, terminating..."
        exit 1
    fi

    eval set -- "${PARAMETERS}"

    util_apply_optstring "$@"
}

util_parse_optstring "$@" 双引号可以避免参数为空或 参数有空格
posted @   LiYanbin  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示