【问题标题】:working with options in bash code [duplicate]使用 bash 代码中的选项 [重复]
【发布时间】:2012-09-29 04:22:11
【问题描述】:

可能重复:
Using getopts in bash shell script to get long and short command line options

我正在尝试弄清楚如何使用诸如 -e/--email -h/--help 之类的标志。

更新: 当前示例:

while getopts ":ec:h" OptionArgument; do
case $OptionArgument in

        e ) S1=${OPTARG};;
        c ) S2=${OPTARG};;
        h ) usage;;
        \?) usage;;
        * ) usage;;
esac
done

但是,如果我留空,它什么也不做。如果我添加 -h 它仍然会运行并且不会显示使用情况。

更新2

while [ $1 ]; do
        case $1 in
                '-h' | '--help' | '?' )
                        usage
                        exit
                        ;;
                '--conf' | '-c' )

                        ;;
                '--email' | '-e' )
                        EMAIL=$1
                        ;;
                * )
                        usage
                        exit
                        ;;
        esac
        shift
done

-h/--help 有效,但其他一切都失败并显示使用情况。

【问题讨论】:

  • Bash 的getopts 不支持长参数,只支持一个字母。请参阅this answer 了解 GNU 的 getopt 来做你想做的事。
  • 更新了问题,到目前为止它成功了一半
  • 对于--email 的情况,您需要一个额外的shiftEMAIL=$2

标签: bash shell getopt getopt-long getopts


【解决方案1】:

如果您想要长的类似 GNU 的选项 短的选项,请参阅此脚本以在您的脚本http://stchaz.free.fr/getopts_long.sh 中获取源代码和示例:

例子:

#!/bin/bash
# ( long_option ) 0 or no_argument,
# 1 or required_argument, 2 or optional_argument).

Help() {
cat<<HELP
Usage :
    $0 [ --install-modules <liste des modules> ] [-h|--help]
HELP
    exit 0
}

. /PATH/TO/getopts_long.sh

OPTLIND=1
while getopts_long :h opt \
    install-modules 1 \
    help 0 "" "$@"
do
    case "$opt" in
        install-modules)
            echo $OPTLARG
        ;;
        h|help)
            Help; exit 0
        ;;
        :)
           printf >&2 '%s: %s\n' "${0##*/}" "$OPTLERR"
           Help
           exit 1
        ;;
    esac
done
shift "$(($OPTLIND - 1))"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多