linux - BASH:根据其他变量的开头设置变量(可能是多个值)

标签 linux bash if-statement

我正在尝试根据 $EnvironmentGroup 设置的内容来设置 $Environment 变量。我认为结合 untilif 会起作用,但我最终得到一个空变量。任何帮助表示赞赏:)

until [ -n $Environment ]
  do
    if [ $EnvironmentGroup -eq ^dev* ]
    then Environment=dev
    break
    fi
    if [ $EnvironmentGroup -eq ^sit* ]
    then Environment=sit
    break
    fi
    if [ $EnvironmentGroup -eq ^uat* ]
    then Environment=uat
    break
    fi
    if [ $EnvironmentGroup -eq ^prod* ]
    then Environment=prod
    break
    fi
done

最佳答案

不确定在这种情况下提示使用 until 的是什么。尽管如此,您实际上并不需要这里的循环甚至多个条件。您可以使用二元运算符 =~:

[[ $EnvironmentGroup =~ ^(dev|sit|uat|prod) ]] && Environment="${BASH_REMATCH[1]}"

这将根据 EnvironmentGroup 的开头(给定的 4 个选项)设置 Environment

此外,您不能在测试中使用 globs,即 [, condition.

引用手册:

Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

关于linux - BASH:根据其他变量的开头设置变量(可能是多个值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23381343/

相关文章:

parsing - 在 UNIX 中创建二进制文件

arrays - AWK 输出到 bash 数组

linux - QTCreator 复制文件

linux - Linux nvme驱动中core.c和pci.c的区别

linux - 在 bash 中使用单引号仍然给出 "event not found"

javascript - 带有 css 值的 jQuery/javascript if 语句

Java - 根据条件将 for 循环计数器转回原处

java - 如何修复 if 语句中的 if 语句?

在 C 中计算文件的 MD5 校验和而不打开文件?

c - 如果我只有设备缓冲区 (PCIe) 的物理地址,我该如何将此缓冲区映射到用户空间?