如何将长选项与 Bash getopts 内置一起使用?

2024-05-13

我正在尝试解析-tempBash getopts 的选项。我这样调用我的脚本:

./myscript -temp /foo/bar/someFile

这是我用来解析选项的代码。

while getopts "temp:shots:o:" option; do
    case $option in
        temp) TMPDIR="$OPTARG" ;;
        shots) NUMSHOTS="$OPTARG" ;;
        o) OUTFILE="$OPTARG" ;;
        *) usage ;;
    esac
done
shift $(($OPTIND - 1))

[ $# -lt 1 ] && usage

正如其他人所解释的, getopts 不解析长选项。您可以使用 getopt,但它不可移植(并且它在某些平台上被破坏......)

作为解决方法,您可以实现 shell 循环。这是一个在使用标准 getopts 命令之前将长选项转换为短选项的示例(我认为它更简单):

# Transform long options to short ones
for arg in "$@"; do
  shift
  case "$arg" in
    '--help')   set -- "$@" '-h'   ;;
    '--number') set -- "$@" '-n'   ;;
    '--rest')   set -- "$@" '-r'   ;;
    '--ws')     set -- "$@" '-w'   ;;
    *)          set -- "$@" "$arg" ;;
  esac
done

# Default behavior
number=0; rest=false; ws=false

# Parse short options
OPTIND=1
while getopts "hn:rw" opt
do
  case "$opt" in
    'h') print_usage; exit 0 ;;
    'n') number=$OPTARG ;;
    'r') rest=true ;;
    'w') ws=true ;;
    '?') print_usage >&2; exit 1 ;;
  esac
done
shift $(expr $OPTIND - 1) # remove options from positional parameters
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将长选项与 Bash getopts 内置一起使用? 的相关文章