28

I would like to be able to use an environment variable if it's set or a default fallback value that I set in pom.xml similar to ${VARIABLE:-default} in bash. Is it possible? Something like:

${env.BUILD_NUMBER:0}
Gavriel
  • 18,880
  • 12
  • 68
  • 105

2 Answers2

48

I wasn't really satisfied with the accepted approach, so I simplified it a little.

Basically set a default property in the normal properties block, and only override when appropriate (instead of an effective switch statement):

<properties>
     <!-- Sane default -->
    <buildNumber>0</buildNumber>
    <!-- the other props you use -->
</properties>

<profiles>
    <profile>
        <id>ci</id>
        <activation>
            <property>
                <name>env.buildNumber</name>
            </property>
        </activation>
        <properties>
            <!-- Override only if necessary -->
            <buildNumber>${env.buildNumber}</buildNumber>
        </properties>
    </profile>
</profiles>
nerdwaller
  • 1,813
  • 1
  • 18
  • 19
24

You could use profiles to achieve this:

<profiles> 
    <profile>
        <id>buildnumber-defined</id>
        <activation>
            <property>
                <name>env.BUILD_NUMBER</name>
            </property>
        </activation>
        <properties>
            <buildnumber>${env.BUILD_NUMBER}</buildnumber>
        </properties>
    </profile>
    <profile>
        <id>buildnumber-undefined</id>
        <activation>
            <property>
                <name>!env.BUILD_NUMBER</name>
            </property>
        </activation>
        <properties>
            <buildnumber>0</buildnumber>
        </properties>
    </profile>
</profiles>

A bit more verbose than bash...

Gavriel
  • 18,880
  • 12
  • 68
  • 105
StephaneM
  • 4,779
  • 1
  • 16
  • 33
  • As far as I know I would need to pass `mvn -P buildnumber-undefined`, don't I? How would I use it later in the pom.xml? – Gavriel Jan 12 '16 at 15:35
  • The appropriate profile will be activated based on the existence or non-existence of the environment variable `BUILD_NUMBER`. Afterwards the property `buildnumber` should be defined in your pom and can be accessed with `${buildnumber}`. – StephaneM Jan 12 '16 at 15:39
  • 3
    As far as I know, you don't need two profiles for this (at least in recent maven releases). You can provide a default in the top level `` and then it's only overridden with the custom activation (the first profile in this answer). Saves 11 lines :) – nerdwaller Aug 17 '16 at 17:37
  • @nerdwaller can you please provide an example? Yours sounds like a better approach. – eggonlegs Nov 22 '16 at 20:45
  • 1
    @eggonlegs - added as an answer so the formatting would show. – nerdwaller Nov 23 '16 at 04:42