【问题标题】:How can I extract a numeric suffix from a string with /bin/sh instead of bash?如何使用 /bin/sh 而不是 bash 从字符串中提取数字后缀?
【发布时间】:2021-05-01 15:01:15
【问题描述】:

我使用 bash 使以下几行工作得很好。

   [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
   ordinal=${BASH_REMATCH[1]}

很遗憾,我无法访问此容器中的 bash,我正在使用 /bin/sh

第一行报错

[[ `hostname` =~ -([0-9]+)$ ]] || exit 1
ash: syntax error: unexpected "("

我假设第二行即使第一行也行不通:-(

主机名包含以 -n 结尾的名称,其中 n 是数字 0、1、2 等。

即myapp-0 或 myapp-1

我只需要上面创建的序数变量中的数字。

正如我所说,在 bash 中效果很好,但不使用 SH shell。

这里是实际报告的 shell(使用 /bin/sh 因为没有安装 bash)

/ # echo $0
ash

有人帮忙吗?

提前致谢。

【问题讨论】:

  • 基本 posix sh 不理解 [[ 或正则表达式或数组,没有。
  • 双方括号[[ ... ]] 是一种bashism,这意味着它们不能保证在符合POSIX 的shell 上工作。如果您需要使用sh,那么您需要创建一个它可以识别的测试表达式。此外,sh 也不知道数组是什么。最后一点,在您的错误消息中,您的 shell 实际上是 ash - 这些区别很重要,因为每个 shell 实现都有自己的怪癖和警告。见unix.stackexchange.com/a/44916
  • 这就像在问“为什么 C 编译器不能运行我的 C++ 代码?” -- 不应该这样。
  • ...我编辑了标题来问你真正的问题——不是你为什么在 /bin/sh 中得到错误,而是如何用它来实现你的目标。
  • 也就是说,请注意 POSIX 根本不需要设置 HOSTNAME。

标签: shell sh


【解决方案1】:

在这种特殊情况下,您根本不需要使用正则表达式来完成这项工作。

#!/bin/sh

# Be cautious here: a real baseline POSIX sh may not have a HOSTNAME variable at all
[ -z "$HOSTNAME" ] && HOSTNAME=$(uname -n)

suffix=${HOSTNAME##*-}
case $suffix in
  # bad case: we have a nonempty suffix variable, but it has a non-numeric digit
  # this can also happen if the hostname has no dash at all, so the PE did nothing
  *[![:digit:]]*) echo "WARNING: No ordinal hostname suffix found" >&2;;

  # happy case: we have a numeric digit, and we know from the above no nonnumerics exist
  [[:digit:]]*)   ordinal=$suffix;;

  # other case: only way this should be reachable is if the hostname ends with a dash
  *)              echo "WARNING: Empty hostname suffix found -- ends with a dash?" >&2;;
esac

echo "Host ordinal value: $ordinal"

这结合了两种技术:

  • parameter expansion${HOSTNAME##*-},删除 HOSTNAME 中直到最后一个 - 的所有内容。 (请注意,POSIX sh 指定的参数扩展比 bash 包含的要少,因此检查您可能想要使用的任何单个扩展是否包含在标准化子集中很重要)。
  • case statement 针对该操作的结果运行 glob 表达式。

【讨论】:

    猜你喜欢
    • 2023-02-07
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2011-04-03
    相关资源
    最近更新 更多