getopt和getopts都是Bash中用来获取与分析命令行参数的工具,常用在shell脚本中被用来分析脚本参数,二者比较:

  • getopts是shell的内建命令,getopt是一个独立外部工具
  • getopts不支持长参数,只能单字母解析,getopt支持长参数
  • getopts不会重排所有参数的顺序,getopt会

getopts

#!/bin/bash
while getopts "a🅱️c" arg [[选项后面的冒号表示该选项需要参数]]
do
    case $arg in
        a)
            echo "a = $OPTARG" [[参数存在]]$OPTARG中
            ;;
        b)
            echo "b = $OPTARG"
            ;;
        c)
            echo "c = $OPTARG" [[因为c后面没接]]: 所以没有参数
            ;;
        ?)  [[当输入除a]] b c的参数外,arg都表示?
            echo "unkonw argument"
            exit 1
        ;;
    esac
done

getopt

ARGS=`getopt -o "ao:" -l "arg,option:" -n "getopt.sh" -- "$@"`
eval set -- "${ARGS}"

参考:

1、shell 命令行参数(getopt和getopts)