Search code examples
bashpcreposix-ere

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/

I want to negate match the version part, and got LUAJIT_VERSION="2.1.0-beta3" at the beginning of bash script. I use:

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

But it seems not working whether I put $LUAJIT_VERSION between "" or not:

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

Can you tell me what's the correct way to do this task?


Solution

  • \s is not a recognized character class in bash; you need to use [[:blank:]] instead:

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

    (The trailing .* isn't necessary, since regular expressions aren't anchored to the start or end of the string.)


    However, it's not clear your regular expression needs to be that general. It looks like you can use a single, literal space

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

    or simply use pattern matching:

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