DEV Community

Cover image for Parsing maven version with bash
Pavel Polívka
Pavel Polívka

Posted on

4 1

Parsing maven version with bash

Recently I needed to parse my pom.xml file to get the artifact version out of it. I needed it on one of our CI agents and I did not have maven installed. I wrote a bash command to parse.

Here it is

grep version pom.xml | grep -v -e '<?xml|~'| head -n 1 | sed 's/[[:space:]]//g' | sed -E 's/<.{0,1}version>//g' | awk '{print $1}'

Let’s go over it step by step to help us understand it better

  • grep version pom.xml - this till get you all the lines with word version in them
  • grep –v –e '<?xml|~' – this will exclude all the matches (-v is reverse match) that are matching the regex (-e), there can be XML specification in the POM file
  • head –n 1 - only the first match
  • sed 's/[[:space:]]//g' - this removes the spaces around/in version string
  • sed -E 's/<.{0,1}version>//g' - this removed the <version> and </version> tags
  • awk '{print $1}' - prints the result

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (2)

Collapse
 
khmarbaise profile image
Karl Heinz Marbaise

I would like to suggest a simpler and safer solution:

VERSION=$(mvn org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate -Dexpression=project.version))
Enter fullscreen mode Exit fullscreen mode

And if you have a ci agent you can run Maven on it...or you can use the CI like Jenkins and read the pom file like this:
github.com/jenkinsci/pipeline-exam...

Usually using a CI will do the installation of Maven automatically on the node for example as Jenkins does...

Collapse
 
bendem profile image
bendem

Don't parse xml without an xml parser, it is not mandatory that the first version tag is the one of your project, it could be the parent pom, it could be anything... Maven provides you with the tools to access all of its data (see dev.to/khmarbaise/comment/14ndf).

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more