【问题标题】:How to support both short and long options at the same time in bash? [duplicate]如何在 bash 中同时支持短选项和长选项? [复制]
【发布时间】:2011-05-10 00:21:36
【问题描述】:

我想在bash 脚本中同时支持短选项和长选项,因此可以:

$ foo -ax --long-key val -b -y SOME FILE NAMES

有可能吗?

【问题讨论】:

  • BashFAQ/035
  • 虽然指定的副本专门询问getopts,但有几个答案建议不同的方法。我同意关闭。

标签: bash getopt getopt-long


【解决方案1】:

getopt 支持长选项。

http://man7.org/linux/man-pages/man1/getopt.1.html

这是一个使用你的论点的例子:

#!/bin/bash

OPTS=`getopt -o axby -l long-key: -- "$@"`
if [ $? != 0 ]
then
    exit 1
fi

eval set -- "$OPTS"

while true ; do
    case "$1" in
        -a) echo "Got a"; shift;;
        -b) echo "Got b"; shift;;
        -x) echo "Got x"; shift;;
        -y) echo "Got y"; shift;;
        --long-key) echo "Got long-key, arg: $2"; shift 2;;
        --) shift; break;;
    esac
done
echo "Args:"
for arg
do
    echo $arg
done

$ foo -ax --long-key val -b -y SOME FILE NAMES的输出:

Got a
Got x
Got long-key, arg: val
Got b
Got y
Args:
SOME
FILE
NAMES

【讨论】:

猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 2023-03-08
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多