无法解决 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 2
        ;;
    -f | --from)
        FROM=$2;
        shift 2
        ;;
    -t | --to)
        TO=$2;
        shift 2
        ;;
    --)
        shift
        break
        ;;
    esac
    shift
done

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

当我尝试运行它时,没有任何反应,它只是挂起:

# bash getopt_check.sh -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

解决方法

您为每个选项移动 3 个值,-d hello.com 是 2 个位置,而不是三个。

-d | --domain)
    ...
    shift 2
    ...
-f | --from)
    ...
    shift 2
    ...
-t | --to)
    ...
    shift 2
    ...
shift             # shift 2 + shift = shift 3!

改为:

-d|--domain)
    shift
    ...
-f|--from)
    shift
    ...
-t|--to)
    shift
    ...
shift

倾向于在脚本中使用小写变量 - 对导出的变量使用大写。使用 http://shellcheck.net 检查您的脚本。最好不要使用 $?,而是检查 if 中的命令,如 if ! options=$(getopt ...); then echo "Incorrect...

while true; do 是不安全的,如果您不处理某些选项,它将无限循环。在 case 语句中执行 while (($#)); do 并处理 *) echo "Internal error - I forgot to add case for my option" >&2; exit 1; ;;