【问题标题】:Use getopts like getopt on shell在 shell 上使用 getopt 之类的 getopt
【发布时间】:2015-01-03 19:23:22
【问题描述】:

系统:freebsd 9.2

我想使用 getopts 来解析命令行。比如

./tesh.sh -o good a.c  
can get  good.out

./tesh.sh -o a.c   
can get a.out

但在 getopts 中没有“选项”变量。 有谁知道如何解决这个问题? 找了很多网页,没有人能解决。

这是我的代码

#!/bin/bash


while getopts "hs:o:" optname
do
    case "$optname" in
    "h")
        echo "Option $optname is specified"
        ;;
    "s")
        echo "Option $optname has value $OPTARG"
        ;;
    "o")    
        echo "$optname"
        ;;
    "?")
        echo "Unknown option $OPTARG"
        ;;
    ":")
    ;;
    *)
        # Should not occur
        echo "Unknown error while processing options"
        ;;
    esac
    echo "OPTIND is now $OPTIND"
done    

如果我输入 ./test.sh -o a.c 它将打印 echo "$optname"

我想要那个 如果我输入 ./test.sh -o 也可以打印 echo "$optname"

现在它会打印错误信息

谢谢!

【问题讨论】:

  • 详细说明您的方案,因为您的要求并不清楚和混淆。
  • Shell script templates;答案的一部分概述了如何使用getopts 解析命令行。您也可以在Using getopts in Bash shell script to get long and short command line options 中找到有用的信息。
  • @SriharshaKalluru 谢谢!我添加了更多关于我的问题
  • @JonathanLeffler 谢谢!但我可以找到我想要的解决方案 =(
  • 如果您定义需要参数的“-o”选项并且您没有提供参数,则会收到错误消息。

标签: bash shell getopt getopts


【解决方案1】:

根据您的要求,您不需要使用 getopts,您可以使用以下代码来实现它。

如果只给出-o,它将被视为一个标志。 如果 -o 被赋予任何值,则它被视为选项。

> cat test
#!/bin/bash

while [ $# -gt 0 ]; do
case $1 in
        -h) echo "Option $optname is specified" ;;
        -s) VAL_S=$2; echo "Option $optname has value $VAL_S" ;shift;;
        -o) VAL_O=$2; F=$(echo $VAL_O |cut -c1);
            if [ "$F" = "-" -o -z "$F" ]; then
                echo "-o is a flag"
                DEFAULT=a.c
            else
                echo "-o is a option"
                DEFAULT=$VAL_O
                shift
            fi
        ;;
        *) echo "Unknown option $OPTARG" ;exit ;;
esac
shift
done

我在可能的情况下运行它。

> ./test -o
-o is a flag
> ./test -o a.c
-o is a option
> ./test -o -h
-o is a flag
Option  is specified
> ./test -o a.c -h
-o is a option
Option  is specified

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多