【问题标题】:Parsing long command-line arguments not working with getopt解析长命令行参数不适用于 getopt
【发布时间】:2021-07-26 14:54:52
【问题描述】:

我想在当前项目中解析大型脚本的长命令行参数。之前从未尝试过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 selection -d|--domain ?.

【问题讨论】:

    标签: bash getopt getopts


    【解决方案1】:

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

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

    而不是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 2013-03-21
      相关资源
      最近更新 更多