util-linux 的 getopt 忽略第一个参数

Maj*_*imi 1 command-line arguments

我按照 stackexchange 网站上的帖子来解析命令行参数。我的程序只解析长参数,所有参数都是强制性的。这是我所做的:

getopt --test > /dev/null
if [[ $? -ne 4 ]]; then
    echo "getopt --test failed in this environment."
    exit 1
fi

function quit {
    echo "$1"
    exit 1
}

# Option strings
LONG="producer-dir:,consumer-dir:,username:,password:,url:,kafka-host:,checkpoint-dir:"

# read the options
OPTS=$(getopt --longoptions ${LONG} --name "$0" -- "$@")
if [ $? != 0 ]; then 
    quit "Failed to parse options...exiting."
fi

eval set -- "$OPTS"

# extract options and their arguments into variables.
while true ; do
  case "$1" in
    --producer-dir )
      PRODUCER_DIR="$2"
      shift 2
      ;;
    --consumer-dir )
      CONSUMER_DIR="$2"
      shift 2
      ;;
    --username )
      USERNAME="$2"
      shift 2
      ;;
    --password )
      PASSWORD="$2"
      shift 2
      ;;
    --url )
      URL="$2"
      shift 2
      ;;
    --kafka-host )
      KAFKA_HOST="$2"
      shift 2
      ;;
    --checkpoint-dir )
      CHECKPOINT_DIR="$2"
      shift 2
      ;;
    -- )
      shift
      break
      ;;
    *)
      echo "Internal error!"
      exit 1
      ;;
  esac
done
Run Code Online (Sandbox Code Playgroud)

无论我以哪种顺序传递参数,第一个都会被忽略,结果为空。其余参数按预期解析。我错过了什么?

use*_*316 5

我认为正在发生的事情是您打算作为第一个参数的内容被解释getoptoptstring. getopt手册页的开头列出了三个概要。您似乎正在使用第二个:

`getopt [options] [--] optstring parameters`
Run Code Online (Sandbox Code Playgroud)

请注意--在第一项之后是 not parameters, but optstring

当我们在做的时候,我应该提到 bash 有一个内部版本getoptgetopts用尾随的s. 在所有其他条件相同的情况下,使用 bash 的内部功能应该更有效。