如何获取 Maven 项目版本到 bash 命令行 [英] How to get Maven project version to the bash command line
问题描述
之前我发布了一个关于如何从命令行更改Maven项目版本的问题 这让我想到了一个新问题.
Previous I issued a question on how to change Maven project vesion from command line which lead me to a new issue.
以前我能够获取版本号,因为版本存储为易于从命令行 (bash) 进行 grep 和解析的属性.现在 pom.xml <version>
元素用于此目的,它不再是唯一的,因为所有依赖项以及其他一些依赖项也使用它.我认为没有办法使用 bash 脚本获取当前版本号没有用于解析 XML 的外部工具或一些非常上下文感知的 sed
命令.
Previously I was able to get the version number since the version was stored as a property that was easy to grep and parse from the command line (bash). Now that the pom.xml <version>
element is used for this, it no longer is unique since all the dependencies and maybe some others too use this. I think there is no way to get the current version number with a bash script without external tools for parsing XML or some very context-aware sed
command.
我认为最干净的解决方案是让 Maven 分发此版本信息.我正在考虑编写一个自定义的 maven 插件来检索不同的属性,但我想我会先在这里问.
The most clean solution in my opinion would be for Maven to hand out this version information. I was thinking of writing a custom maven plugin for retrieving different properties but I thought I'd ask here first.
那么,有没有什么简单的方法可以将 ${project.version}
的值放到命令行中?
So, is there any easy way to get the value of ${project.version}
to the command line?
我必须手动cd
到目录,但这可以轻松完成.在我的 bash 脚本中,我有:
I had to cd
to the directory manually but that can be done easily. In my bash script I have:
version=`cd $project_loc && mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | sed -n -e '/^[.*]/ !{ /^[0-9]/ { p; q } }'`
这为我提供了可以推进的当前版本.Grepping 可能更简单,但我想我想要尽可能健壮,所以我对以数字开头的第一行感到满意,并尝试将其作为版本号处理.
Which gives me the current version that I can then advance. Grepping might be simpler but I thought I'd like as robust as possible, so I'm satisfied with the first line that starts with a number and try to handle this as a version number.
# Advances the last number of the given version string by one.
function advance_version () {
local v=$1
# Get the last number. First remove any suffixes (such as '-SNAPSHOT').
local cleaned=`echo $v | sed -e 's/[^0-9][^0-9]*$//'`
local last_num=`echo $cleaned | sed -e 's/[0-9]*.//g'`
local next_num=$(($last_num+1))
# Finally replace the last number in version string with the new one.
echo $v | sed -e "s/[0-9][0-9]*([^0-9]*)$/$next_num/"
}
我通过简单地调用来使用它:
And I use this by simply calling:
new_version=$(advance_version $version)
推荐答案
Tom's solution with the ExecMaven 插件要好得多,但仍然比它需要的要复杂.对我来说很简单:
Tom's solution with the Exec Maven Plugin is much better, but still more complicated than it needs to be. For me it's as simple as:
MVN_VERSION=$(mvn -q
-Dexec.executable=echo
-Dexec.args='${project.version}'
--non-recursive
exec:exec)
这篇关于如何获取 Maven 项目版本到 bash 命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!