shell 使用getopt将第二个参数解析为变量

63lcw9qa  于 2022-12-13  发布在  Shell
关注(0)|答案(1)|浏览(104)

如何在以下脚本中使用bashgetopt将第二个参数解析为变量。
我可以执行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而不出现Invalid option testuser错误?
输出:

>sh test3.sh -u testuser
userENT

Invalid option testuser
user testuser
tmb3ates

tmb3ates1#

man getopt会告诉你选项后面的冒号表示它有一个参数。你只有在v后面有一个冒号。你也没有在循环中使用shift,所以你不能解析第一个选项之后的任何选项。我不知道为什么你觉得需要第二个case语句,它只有一个默认选项。另外,你的代码中有很多不好的做法,包括使用全大写的变量名和反勾号而不是$()来执行命令。你把问题标记为bash,但你的问题是/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"

相关问题