Channels ▼

Open Source

Writing Build Scripts With Gradle

In the first installment of this series on Gradle, I compared existing Java build tools with Gradle and described Gradle's compelling features. In this article, I show how to write and run Gradle's build scripts.

Installing Gradle

Before installing Gradle, make sure you've already installed the JDK with a version of 1.5 or higher. Even though some operating systems provide you with an out-of-the-box Java installation, make sure you have a valid version installed on your system. To check the JDK version, run java –version.

To get started with Gradle, download the distribution directly from the Gradle homepage. As a beginner to the tool, it makes sense to choose the ZIP file that includes the documentation and a wide range of source code examples to explore. Unzip the downloaded file to a directory of your choice. To reference your Gradle runtime in the shell, you'll need to create the environment variable GRADLE_HOME and add the binaries to your shell's execution path:

  • Mac OS X and *nix: To make Gradle available in your shell, add the following two lines to your initialization script (for example, ~/.profile). These instructions assume that you installed Gradle in the directory /opt/gradle:
    export GRADLE_HOME=/opt/gradle
    export PATH=$PATH:$GRADLE_HOME/bin
  • Windows: In the dialog environment variable, define the variable GRADLE_HOME and update your path settings (Figure 1).

Figure 1: Updating variable settings on Windows.

You'll verify that Gradle has been installed correctly and is ready to go. To check the version of the installed runtime, issue the command gradle –v in your shell. You should see meta-information about the installation, your JVM, and the operating system. The following example shows the version output of a successful Gradle 1.7 installation.

$ gradle –v

Gradle 1.7

Build time:   2013-08-06 11:19:56 UTC
Build number: none
Revision:     9a7199efaf72c620b33f9767874f0ebced135d83

Groovy:       1.8.6
Ant:          Apache Ant(TM) version 1.8.4 compiled on May 22 2012
Ivy:          2.2.0
JVM:          1.6.0_51 (Apple Inc. 20.51-b01-457)
OS:           Mac OS X 10.8.4 x86_64

Setting Gradle's JVM Options

Note that like every other Java application, Gradle shares the same JVM options set by the environment variable JAVA_OPTS. If you want to pass arguments specifically to the Gradle runtime, use the environment variable GRADLE_OPTS. Let's say you want to increase the default maximum heap size to 1 GB. You could set it like this:


Although, the preferred way to do that is to add the variable to the Gradle startup script under $GRADLE_HOME/bin.

Now, let's implement a simple build script with Gradle. Even though most of the popular IDEs provide a Gradle plugin, all you need now is your favorite editor. Gradle plugin support exists for IDEs such as IntelliJ IDEA, Eclipse, and NetBeans.

Getting started with Gradle

Every Gradle build starts with a script. The default naming convention for a Gradle build script is build.gradle. When executing the command gradle in a shell, Gradle looks for a file with that exact name. If it can't be located, the runtime will display a help message.

Let's set the lofty goal of creating the typical "Hello world!" example in Gradle. First, create a file called build.gradle. Within that script, define a single atomic piece of work. In Gradle's vocabulary, this is called a task. In this example, the task is called helloWorld. To print the message “Hello world!” make use of Gradle's primary language, Groovy, by adding the println command to the task's action doLast. The method println is Groovy's shorter equivalent to Java's System.out.println:

task helloWorld {
   doLast {
      println 'Hello world!'

Give it a spin:

$ gradle –q helloWorld
Hello world!

As expected, you see the output “Hello world!” when running the script. By defining the optional command-line option quiet with –q, you tell Gradle to only output the task's output.

Without knowing it, you already used Gradle's DSL. Tasks and actions are important elements of the language. An action named doLast is almost self-expressive. It's the last action that's executed for a task. Gradle allows for specifying the same logic in a more concise way. The left shift operator << is a shortcut for the action doLast. The following snippet shows a modified version of the first example:

task helloWorld << {
   println 'Hello world!'

Printing "Hello world!" only goes so far. I'll give you a taste of more-advanced features in the example build script shown in Listing One.

task startSession << {
def chant() {
    ant.echo(message: 'Repeat after me...')
3.times {
    task "yayGradle$it" << {
        println 'Gradle rocks'
yayGradle0.dependsOn startSession
yayGradle2.dependsOn yayGradle1, yayGradle0
task groupTherapy(dependsOn: yayGradle2)

Listing One: Dynamic task definition and task chaining.

You may not notice it at first, but there's a lot going on in this listing. You introduced the keyword dependsOn to indicate dependencies between tasks. Gradle makes sure that the depended-on task will always be executed before the task that defines the dependency. Under the hood, dependsOn is actually a method of a task.

A feature I talked about in the first installment in this series is Gradle's tight integration with Ant. Because you have full access to Groovy's language features, you can also print your message in a method named chant(). This method can easily be called from your task. Every script is equipped with a property called ant that grants direct access to Ant tasks. In this example, you printed out the message "Repeat after me" using the Ant task echo to start the therapy session.

A nifty feature Gradle provides is the definition of dynamic tasks, which specify their name at runtime. Your script creates three new tasks within a loop using Groovy's times method extension on java.lang.Number. Groovy automatically exposes an implicit variable named it to indicate the loop iteration index. You're using this counter to build the task name. For the first iteration, the task would be called yayGradle0.

Now running gradle groupTherapy results in the following output:

$ gradle groupTherapy
[ant:echo] Repeat after me...
Gradle rocks
Gradle rocks
Gradle rocks

As shown in Figure 2 Gradle executed the tasks in the correct order. You may have noticed that the example omitted the quiet command-line option, which gives more information on the tasks run.

Figure 2: Task dependency graph.

Now, let's get more accustomed to Gradle's command line.

Using the Command Line

You just executed the tasks helloWorld and groupTherapy on the command line, which is going to be your tool of choice for learning. Even though using an IDE may seem more convenient to newcomers, a deep understanding of Gradle's command-line options and helper tasks will make you more efficient and productive in the long run.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.