DEV Community

Cover image for A simple Gradle build with example on Ubuntu
Kinjal
Kinjal

Posted on

A simple Gradle build with example on Ubuntu

Gradle is a higly customizable, powerful and fast build system.
Let's walk through a simple example to configure a project using gradle.

First, download a specific release.

Here are the steps to configure it.

$ mkdir /opt/gradle
$ unzip -d /opt/gradle gradle-7.2-bin.zip
$ ls /opt/gradle/gradle-7.2/
LICENSE  NOTICE  README  bin  init.d  lib  
Enter fullscreen mode Exit fullscreen mode

Add the following line in ~/.bashrc.

export PATH=$HOME/.local/bin:$PATH 
Enter fullscreen mode Exit fullscreen mode

~/.bashrc file should be updated to get the changes.

$ source ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

Run gradle -version when the above steps are completed.
gradle version

Let's call the project name blue and scaffold gradle for it.

$ mkdir blue
$ cd blue
$ gradle init
Enter fullscreen mode Exit fullscreen mode

It will ask few to setup the directory strucutre

Select type of project to generate:
 1. basic
 2. application
 3. library
 4. Gradle plugin
Enter fullscreen mode Exit fullscreen mode

For this example, let's select 2. application.

The following question will ask selecting the implementation language which I choose java.

The other options could be selected as per the given default choice.

Let's create a makefile and add some basic gradle commands there.

$ cat makefile
 JAVA_HOME = /opt/sun/jdk15
 GRADLE_HOME = /opt/gradle/gradle-7.2

 GRADLE = $(GRADLE_HOME)/bin/gradle
 clean:
       ./gradlew clean  
 build:
      ./gradlew build
 run:
      ./gradlew run
 test:
      gradle test --tests AppTest 
Enter fullscreen mode Exit fullscreen mode

App.java which is located in app/src/main/java/blue/ is the entry point to the project.
Edit this class and add soem message to it.

package blue;

public class App {
 private String getMessage() { return "My Gradle Project"; } 

 public static void main(String[] args) {
   App app = new App();
   System.out.println(app.getMessage());
 }
}
Enter fullscreen mode Exit fullscreen mode

Now, run the project.

$ make build
$ make run
Enter fullscreen mode Exit fullscreen mode

The sample message should be printed in the console if the build is successful.

Download this sample.

Discussion (0)