bash - 使用不带参数的 getopts 获取帮助输出

标签 bash arguments getopt manpage getopts

您好,我正在创建一个使用 getopts 的 bash 脚本。 现在我想创建一个“-h”参数来获得帮助。 但是每次我都必须为参数提供一个参数。

Now

test.sh -h test

What I want

test.sh -h
help
help
help



while getopts :c:s:d:h:I:p:r FLAG; do
  case $FLAG in


        s)
                SOURCE=$OPTARG
                ;;
        d)
                DESTINATION=$OPTARG
                ;;
        I)
                ISSUE=$OPTARG
                ;;
        c)
                CUSTOMER=$OPTARG
                test -e /etc/squid3/conf.d/$CUSTOMER.conf
                customer_available=$?
                ;;
        p)
                PORT=$OPTARG
                ;;
        h)      HELP=$OPTARG
                echo help

最佳答案

选项后的 : 表示该选项需要一个参数。

OPTARG 变量包含您传递给选项的参数。

如果您不需要参数,请删除 h 之后的 : 以及 HELP=$OPTARG 行。

while getopts :c:s:d:hI:p:r FLAG; do
...
     h)      echo help
...
done

如需进一步引用,请查看此 link .

关于bash - 使用不带参数的 getopts 获取帮助输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38742108/

相关文章:

C : Use getopt with an option which takes an optional parameter

c - 是否可以重复getopt

ruby - 为什么字符串索引返回一个整数值而不是一个字符?

c - C 结构中函数的参数

linux - Shell 脚本以及如何避免在 Linux 机器上同时运行相同的脚本

c - 两个或多个命令行参数?

java - 寻找基于AOP和注解的方法参数验证框架

c - 如何从 optarg 获取值

linux - 在 bash 中用 ' ' 替换 '\'

bash - 如何使用 Bash 递归地创建不存在的子目录?