Nicholas Marshall
Nicholas Marshall

Reputation: 3238

In Gradle, is there a better way to get Environment Variables?

In several Tasks, I reference jars in my home folder.

Is there a better way to get Environment Variables than

ENV = System.getenv()
HOME = ENV['HOME']

task copyToServer(dependsOn: 'jar', type: Copy) {

 from 'build/libs/'
 into HOME + "/something/plugins/"
}

This sets $HOME but I was hoping that I missed some magic from the documentation.

Upvotes: 211

Views: 245629

Answers (4)

Mahozad
Mahozad

Reputation: 24552

This is for Kotlin DSL (build.gradle.kts):

val myVariable = System.getenv("MY_VARIABLE_NAME") ?: "my default value"

OR

val myVariable = System.getenv("MY_VARIABLE_NAME") ?: error("Env variable not found")

OR

val environment = System.getenv()
val myVariable = environment["MY_VARIABLE_NAME"] ?: "my default value"
// OR val myVariable = environment["MY_VARIABLE_NAME"] ?: error("Env variable not found")

Upvotes: 23

Yochai Timmer
Yochai Timmer

Reputation: 49251

In android gradle 0.4.0 you can just do:

println System.env.HOME

classpath com.android.tools.build:gradle-experimental:0.4.0

Upvotes: 13

Jarett Millard
Jarett Millard

Reputation: 5958

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

Upvotes: 147

thoredge
thoredge

Reputation: 12601

Well; this works as well:

home = "$System.env.HOME"

It's not clear what you're aiming for.

Upvotes: 311

Related Questions