解析长命令行参数不适用于 getopt

问题描述

我想解析大型脚本的长命令行参数,作为我当前项目的一部分。我之前从未尝试过 getopt 但想第一次尝试使脚本看起来整洁。

在尝试将 getopt 推送到那个大型项目脚本之前,我想先在示例脚本上检查它。

在下面的示例脚本中,解析短命令行参数可以正常工作,但不能解析长命令行参数:

#!/bin/bash

options=$(getopt -o d:f:t: -l domain -l from -l to -- "$@")

[ $? -eq 0 ] || { 
    echo "Incorrect options provided"
    exit 1
}

eval set -- "$options"

while true; do
    case "$1" in
    -d|--domain)
        DOMAIN=$2;
        shift
        ;;
    -f|--from)
        FROM=$2;
        shift
        ;;
    -t|--to)
        TO=$2;
        shift
        ;;
    --)
        shift
        break
        ;;
    *)
        echo "Invalid options!!";
        exit 1
        ;;
    esac
    shift
done

echo "Domain is $DOMAIN"
echo "From address is $FROM"
echo "To address is $TO"
exit 0;

输出

# ./getopt_check.bash -d hello.com -f from@test.com -t to@test.com
Domain is hello.com
From address is from@test.com
To address is to@test.com

# ./getopt_check.bash --domain hello.com -f from@test.com -t to@test.com
Invalid options!!

# ./getopt_check.bash --domain hello.com --from from@test.com --to to@test.com
Invalid options!!

在解析长命令参数时,我也期待相同的输出

Domain is hello.com
From address is from@test.com
To address is to@test.com

调试时:

# bash -x getopt_check.bash --domain hello.com -f from@test.com -t to@test.com
++ getopt -o d:f:t: -l domain -l from -l to -- --domain hello.com -f from@test.com -t to@test.com
+ options=' --domain -f '\''from@test.com'\'' -t '\''to@test.com'\'' -- '\''hello.com'\'''
+ '[' 0 -eq 0 ']'
+ eval set -- ' --domain -f '\''from@test.com'\'' -t '\''to@test.com'\'' -- '\''hello.com'\'''
++ set -- --domain -f from@test.com -t to@test.com -- hello.com
+ true
+ case "$1" in
+ DOMAIN=-f
+ shift
+ shift
+ true
+ case "$1" in
+ echo 'Invalid options!!'
Invalid options!!
+ exit 1

这里的问题是通过 case switch OR choice -d|--domain ?.

解决方法

我猜是你的 getopt 语法。使用:

getopt -o d:f:t: -l domain:,from:,to: -- "$@"

代替:

getopt -o d:f:t: -l domain -l from -l to -- "$@"