bash 如果没有提供选项,让 getopts 显示帮助

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26592217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:39:18  来源:igfitidea点击:

Having getopts to show help if no options provided

bashgetopts

提问by Omar

I parsed some similar questions posted here but they aren't suitable for me.

我解析了这里发布的一些类似问题,但它们不适合我。

I've got this wonderful bash script which does some cool functions, here is the relevant section of the code:

我有这个很棒的 bash 脚本,它可以执行一些很酷的功能,这是代码的相关部分:

while getopts ":hhelpf:d:c:" ARGS;
do
    case $ARGS in
        h|help )
            help_message >&2
            exit 1
            ;;
        f )
            F_FLAG=1
            LISTEXPORT=$OPTARG
            ;;
        d )
            D_FLAG=1
            OUTPUT=$OPTARG
            ;;
        c )
            CLUSTER=$OPTARG
            ;;
        \? )
            echo ""
            echo "Unimplemented option: -$OPTARG" >&2
            echo ""
            exit 1
            ;;
        : )
            echo ""
            echo "Option -$OPTARG needs an argument." >&2
            echo ""
            exit 1
            ;;
        * )
            help_message >&2
            exit 1
            ;;
    esac
done

Now, all my options works well, if triggered. What I want is getopts to spit out the help_message functionwhen no option is triggered, say the script is launched just ./scriptname.shwithout arguments.

现在,如果触发,我的所有选项都可以正常工作。我想要的是 getopts在没有触发任何选项时吐出help_message 函数,说脚本只是启动./scriptname.sh而不带参数。

I saw some ways posted here, implementing IFcycle and functionsbut, since I'm just starting with bash and I already have some IF cycles on this script, I would like to know if there is an easier (and pretty) way to to this.

我在这里看到了一些实现IF循环和函数的方法,但是,由于我刚刚开始使用 bash 并且我已经在这个脚本上有一些 IF 循环,我想知道是否有更简单(和漂亮)的方法来实现这个。

采纳答案by Omar

Many thanks to Etan Reisner, I ended up using your suggestion:

非常感谢 Etan Reisner,我最终使用了您的建议:

if [ $# -eq 0 ];
then
    help_message
    exit 0
else
...... remainder of script

This works exactly the way I supposed. Thanks.

这完全按照我的想法工作。谢谢。

回答by Etan Reisner

If you just want to detect the script being called with no options then just check the value of $#in your script and exit with a message when it is zero.

如果您只想检测没有选项调用的脚本,那么只需检查$#脚本中的值,并在它为零时退出并显示消息。

If you want to catch the case where no option arguments are passed (but non-option arguments) are still passed then you should be able to check the value of OPTINDafter the getoptsloop and exit when it is 1 (indicating that the first argument is a non-option argument).

如果你想捕捉没有传递选项参数(但非选项参数)仍然传递的情况,那么你应该能够检查循环OPTIND之后的值getopts并在它为 1 时退出(表明第一个参数是一个非选项参数)。