如何使用 bash "=~" 来匹配命令的版本?

How to match version of a command using bash "=~"?

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放在""之间 或不:

Any part of the pattern may be quoted to force the quoted portion to be matched as a string ... If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched as a string.

Bash docs

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

\s 不是 bash 中可识别的字符 class;您需要使用 [[:blank:]] 代替:

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

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


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

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

或者简单地使用模式匹配:

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