Adding Maven dependency with command line

Using the POM directly is probably a better way, but yes you can do that:

mvn install:install-file -Dfile=<path-to-file> -DgroupId="group-id" \
-DartifactId="artifact-id" -Dversion="version" -Dpackaging="packaging"

https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html


I'm not very sure if there's a built-in maven feature or plugin to do so, but I don't think so. You could achieve it by a small script using sed or something similar. I've used the following in a bash script:

get_foo_dep() {
  cat <<EOF
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>foo</artifactId>
        <version>${DEP_VERSION}</version>
    </dependency>
EOF
}

DEP_VERSION="1.0.0"  # just example, you can set it from somewhere
POM_FILE="pom.xml"   # just example, the path to pom

foo_dep=$(get_foo_dep)
foo_dep=${foo_dep//$'\n'/\\$'\n'}   # escape \n with \\n for sed to work
sed -i "s|<dependencies>|<dependencies>\n${foo_dep}|" "$POM_FILE"  # CARE!! it makes in-place substitution

You can also have a look at this other question, where awk is recommended:

Is it possible to use sed to replace dependencies's version in a pom file?