【问题标题】:Unable to workaround on getopt options [closed]无法解决 getopt 选项 [关闭]
【发布时间】:2021-07-26 11:45:39
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • bash -x 运行你的脚本表明getopt 在Bash 5.x 中默默地删除了--。在 Bash 3.x 上,它的工作方式与您所希望的完全一样。投票结束,因为缺乏微不足道的调试工作。
  • 顺便说一句,shell 脚本通常根本不应该有扩展名;如果您使用.sh,则意味着您的脚本针对 POSIX sh,而不是 Bash。
  • it does not produce my required output. 需要的输出是什么?
  • @KamilCuk :感谢您的参与,我编辑了问题。

标签: bash getopt getopts


【解决方案1】:

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

-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 ! options=$(getopt ...); then echo "Incorrect...一样检查if中的命令。

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

【讨论】:

  • 太好了,谢谢一百万,这很有效。我现在意识到我的错误:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
  • 2018-09-07
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
相关资源
最近更新 更多