【问题标题】:bash - using getops to parse second argument into a variablebash - 使用 getops 将第二个参数解析为变量
【发布时间】:2019-04-03 01:28:40
【问题描述】:

如何在以下脚本中使用 bash 和 getopt 将第二个参数解析为变量。

我可以做 sh test.sh -u 并让“userENT”显示。但是如果我在这个脚本上执行 sh test.sh -u testuser 我会得到一个错误。

#!/bin/sh

# Now check for arguments
OPTS=`getopt -o upbdhrstv: --long username,password,docker-build,help,version,\
  release,remote-registry,stage,develop,target: -n 'parse-options' -- "$@"`



while true; do
  case "$1" in
    -u | --username) 
            case "$2" in
               *) API_KEY_ART_USER="$2"; echo "userENT" ;shift ;;
            esac ;;
    -- ) shift; break ;;
    * ) if [ _$1 != "_" ]; then ERROR=true; echo; echo "Invalid option $1"; fi; break ;;

   esac
done
echo "user" $API_KEY_ART_USER

我怎样才能通过 -u testuser 而没有无效选项 testuser?

输出:

>sh test3.sh -u testuser
userENT

Invalid option testuser
user testuser

【问题讨论】:

    标签: bash shell getopt


    【解决方案1】:

    man getopt 会告诉你选项后面的冒号表示它有一个参数。您在 v 之后只有一个冒号。您的循环中也没有 shifting,因此您将无法解析第一个选项之后的任何选项。而且我不确定您为什么觉得需要第二个 case 语句,它只有一个默认选项。此外,您的代码中有许多不良做法,包括使用所有大写变量名称和反引号而不是 $() 来执行命令。你已经标记了你的问题,但你的shebang是/bin/sh。试一试,但你不应该在不了解代码的作用的情况下使用代码。

    #!/bin/sh
    
    # Now check for arguments
    opts=$(getopt -o u:pbdhrstv: --long username:,password,docker-build,help,version,\
        release,remote-registry,stage,develop,target: -n 'parse-options' -- "$@")
    
    while true; do
        case "$1" in
        -u|--username)
            shift
            api_key_art_user="$1"
            echo "userENT"
        ;;
        --)
            shift;
            break
        ;;
        *)
            if [ -n "$1" ]; then 
                err=true
                echo "Invalid option $1"
            fi
            break
        ;;
        esac
        shift
    done
    echo "user $api_key_art_user"
    

    【讨论】:

    • 应该也实际使用getopt(eval set -- "$opts")的输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2017-04-07
    • 2018-09-18
    • 1970-01-01
    • 2022-11-24
    • 2018-12-27
    相关资源
    最近更新 更多