Over a million developers have joined DZone.

Gradle Goodness: Checking Operating Systems in Build Scripts

DZone's Guide to

Gradle Goodness: Checking Operating Systems in Build Scripts

Checking the OS in a build script is a common enough desire. You can do that with Gradle, but you shouldn't use the internal class that, on the face of it, would help.

· Java Zone ·
Free Resource

Atomist automates your software deliver experience. It's how modern teams deliver modern software.

Sometimes, we want to check which operating system is used in our build script. For example, we have tasks that need to run if the operating system is Windows and not for other operating systems. Gradle has an internal class that can help with that:


But we should not use this class in our build scripts. The class is used internally by Gradle and can change without warning. If we depend on this class and it changes, we break our build scripts. But we can use a class from Ant that is already in Gradle's class path:


The class has several methods and constants to check the operating system name, version, and architecture. The values are based on the Java system properties os.name, os.version, and os.arch.

In the following example build script, we use import static to include the Os class, so we can directly invoke the methods and refer to the constants in the Os class. We add some tasks that have a condition check with onlyIf so the task only runs when the condition in the closure is true. The task osInfo simply shows values from the Os class:

// File: build.gradle
import static org.apache.tools.ant.taskdefs.condition.Os.*

task os {
    description 'Run all conditional os tasks'

// Create 3 tasks that simply print
// the task name that is executed
// if the build scripts runs on the
// recognized operating system.

    // Create task.
    tasks.create(osName) {
        description "Run when OS is ${osName}"

        // Add condition to check operating system.
        onlyIf { isFamily(osName) }

        doLast {
            println "Execute task '${it.name}'"

    // Add task as dependency for the os task.
    os.dependsOn osName

task osInfo {
    description 'Show information about the operating system'
    doLast {
        println "Family:       ${OS_NAME}"
        println "Version:      ${OS_VERSION}"
        println "Architecture: ${OS_ARCH}"

Let's run the os and osInfo tasks on MacOS:

$ gradle os osInfo
Execute task 'mac'
Execute task 'unix'
:windows SKIPPED
Family:       mac os x
Version:      10.12.3
Architecture: x86_64


Total time: 0.697 secs

Written with Gradle 3.3.

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

java ,gradle ,build script ,operating systems

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}