【问题标题】:How can I check if the value of argument provided from GETOPTS is equal to specific string?如何检查 GETOPTS 提供的参数值是否等于特定字符串?
【发布时间】:2020-01-27 14:34:39
【问题描述】:

我正在编写 bash 脚本,它将根据提供的参数在本地或远程构建一个 docker 映像。

我正在努力检查提供的字符串是否等于“远程”或“本地”。

当我执行脚本时,它不接受任何数字,但它接受任何字符串。

!/bin/bash

usage() { echo "Usage: $0 [-m < local|remote>]" 1>&2; exit 1; }

while getopts "m:" o; do
    case "${o}" in
        m)
            destination=${OPTARG}
            ((destination == "local" || destination == "remote")) || usage
            ;;
        *)
            usage
            ;;
    esac
done
shift "$((OPTIND-1))"

echo $destination

【问题讨论】:

  • 前段时间有人评论说你不应该使用 getopts 而是在大多数时候只使用普通的参数解析。我现在找不到突出显示原因的确切链接,但也许这就是正确的方法。
  • (( )) 用于算术运算,[[ "$destionation" = local || "$destination" = remote ]] 用于字符串比较
  • [[ "$destionation" = 本地 || "$destination" = remote ]] 添加这些以某种方式帮助了我。现在脚本只接受当前是“远程”的第二个值,但不幸的是它不接受第一个“本地”或“本地”或我称之为的任何其他值。它返回 usage() 的输出。

标签: string bash docker getopts


【解决方案1】:

因此,您真正需要做的唯一更改就是按照@Nahuel Fouilleul 的建议将((...)) 语句更改为[[ ... ]] 语句,并将$ 添加到您的目标变量中。然而,他们的建议对您不起作用,因为目的地拼写错误。我有如下所示的更新代码。

#!/bin/bash

usage() { echo "Usage: $0 [-m < local|remote>]" 1>&2; exit 1; }

while getopts "m:" o; do
  case "${o}" in
    m)
        destination=${OPTARG}
        [[ $destination == "local" || $destination == "remote" ]] || usage
        ;;
    *)
        usage
        ;;
  esac
done

shift "$(( OPTIND-1 ))"

echo $destination

但是,您不需要在 switch 语句中检查此信息,您可以检查代码的主要部分并确保已使用参数扩展设置目标,如下所示:

...
    m)
        destination=${OPTARG}
        ;;
...

[[ ${destination:?A destination is required.} == "local" || ${destination} == "remote" ]] || usage

echo $destination

【讨论】:

  • 你帮了我很多忙!在我检查我的代码是否缺少字符或拼写错误之前,但是当我复制部分代码时我没有注意到这个错误......非常感谢,干杯!
猜你喜欢
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 2018-02-10
相关资源
最近更新 更多