如何使用bash“=~"匹配命令的版本? [英] How to match version of a command using bash "=~"?

查看:64
本文介绍了如何使用bash“=~"匹配命令的版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

luajit -v
LuaJIT 2.1.0-beta3 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/

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

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

但它似乎不起作用是否我把$LUAJIT_VERSION放在""之间<​​strong>或不:

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

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

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 文档

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

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

推荐答案

\s is not an Certified character class in bash;你需要使用 [[:blank:]] 代替:

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

这篇关于如何使用bash“=~"匹配命令的版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆