getopt 使用小结

getopt 是什么

  • bash的getopt命令经常用在shell脚本内部或函数内部,用来解析脚本执行或函数执行时传递的选项、参数。

getopt 如何使用

getopt 命令的模板

getopt -o SHORT_OPTIONS -l LONG_OPTIONS -n "$0" -- "$@"
  • -o 表示后接短选项。
  • -l 表示后接长选项。
  • -n "$0" getopt 在解析命令行时,如果出错。getopt 将使用该 NAME 作为报错的脚本名称。
  • -- 表示 getopt命令自身的选项到此结束,后面的元素是要被 getopt 解析的命令行参数。
  • "$@" 表示所有的命令行参数。

使用场景模板

parameters=$(getopt -o SHORT_OPTIONS -l LONG_OPTIONS -n "$0" -- "$@")
[ $? != 0 ] && exit 1
eval set -- "$parameters"   # 将$parameters设置为位置参数
while true ; do             # 循环解析位置参数
    case "$1" in
        -a|--longa) ...;shift ;;    # 不带参数的选项-a或--longa
        -b|--longb) ...;shift 2;;   # 带参数的选项-b或--longb
        -c|--longc)                 # 参数可选的选项-c或--longc
            case "$2" in 
                "")...;shift 2;;  # 没有给可选参数
                *) ...;shift 2;;  # 给了可选参数
            esac;;
        --) ...; break ;;       # 开始解析非选项类型的参数,break后,它们都保留在$@中
        *) echo "wrong";exit 1;;
    esac
done
posted @ 2022-03-18 07:27  profound-wu  阅读(167)  评论(0)    收藏  举报