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

落花浮王杯 提交于 2019-12-13 03:28:06

问题


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?


回答1:


\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"* ]];


来源:https://stackoverflow.com/questions/49761054/how-to-match-version-of-a-command-using-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!