【问题标题】:How to match version of a command using bash "=~"?如何使用 bash "=~" 匹配命令的版本?
【发布时间】:2018-09-20 12:16:23
【问题描述】:
luajit -v
LuaJIT 2.1.0-beta3 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/

我想否定匹配版本部分,并在bash脚本的开头得到LUAJIT_VERSION="2.1.0-beta3"。我用:

if ! [[ "$(luajit -v)" =~ LuaJIT\s+"$LUAJIT_VERSION".* ]]; then
#rest of code

但它似乎不起作用是否我把$LUAJIT_VERSION放在""之间或没有

可以引用模式的任何部分以强制将引用的部分匹配为字符串...如果模式存储在 shell 变量中,引用变量扩展会强制将整个模式匹配为字符串。

Bash docs

你能告诉我完成这项任务的正确方法是什么吗?

【问题讨论】:

  • 我认为你不能在 Bash 正则表达式中使用 \s
  • @BenjaminW。但它不是扩展正则表达式吗? An additional binary operator, ‘=~’, is available, with the same precedence as ‘==’ and ‘!=’. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly
  • 尝试使用[[:blank:]]而不是\s
  • 是的,但\s 不是 ERE 的一部分。您可以改用字符类[[:blank:]]。对于最小的 POC:尝试[[ ' ' =~ \s ]] || echo "no match"
  • \s 更准确地描述为 Perl 兼容的正则表达式 (PCRE);它不是 POSIX 扩展正则表达式。

标签: bash pcre posix-ere


【解决方案1】:

\s 不是bash 中可识别的字符类;你需要改用[[:blank:]]

if ! [[ "$(luajit -v)" =~ LuaJIT[[:blank:]]+"$LUAJIT_VERSION" ]]; then

(结尾的.* 不是必需的,因为正则表达式没有锚定到字符串的开头或结尾。)


但是,尚不清楚您的正则表达式是否需要如此通用。看起来您可以使用单个文字空间

if ! [[ "$(luajit -v)" =~ LuaJIT\ "$LUAJIT_VERSION" ]];

或者干脆使用模式匹配:

if [[ "$(luajit -v)" != LuaJIT\ "$LUAJIT_VERSION"* ]];

【讨论】:

    猜你喜欢
    • 2015-04-02
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    相关资源
    最近更新 更多