When it comes to automating everyday development tasks, most developers quickly reach for Bash, Python, or Node.js scripts. But did you know Groovy can also be a powerful and flexible scripting language? Originally designed as a dynamic companion to Java, Groovy shines in writing concise scripts that run directly on the JVM.
With Groovy, you can:
-
Write scripts with clean, expressive syntax.
-
Reuse existing Java libraries without extra dependencies.
-
Take advantage of built-in utilities for file handling, process execution, and JSON/XML parsing.
-
Run scripts easily with the
groovy
command, no compilation required.
In this tutorial, we’ll explore how to use Groovy shell scripts for everyday development tasks. We’ll go step by step, showing how Groovy can simplify common jobs like file operations, HTTP requests, JSON processing, and system automation. By the end, you’ll have a handy toolbox of Groovy script examples that you can adapt to your own workflow.
Setting Up Groovy for Scripting
Before diving into scripts, we need to make sure Groovy is installed and ready to use on your system. Groovy runs on the JVM (Java Virtual Machine), so you’ll also need Java installed.
1. Install Java
Make sure Java is installed by running:
java -version
You should see output showing your Java version. Groovy generally works well with the latest Java 17 or Java 21 LTS.
If Java isn’t installed, grab it from Adoptium or use your system package manager (e.g., brew install openjdk
on macOS, apt install openjdk-17-jdk
on Ubuntu).
2. Install Groovy
The easiest way to install Groovy is through SDKMAN! (Software Development Kit Manager).
-
Install SDKMAN:
curl -s "https://get.sdkman.io" | bash source "$HOME/.sdkman/bin/sdkman-init.sh"
-
Install Groovy:
sdk install groovy
-
Verify installation:
groovy -v
You should see the Groovy version printed.
3. Running Your First Groovy Script
Let’s write a simple Groovy script to test the setup.
Create a file called hello.groovy:
println "Hello, Groovy Shell!"
Run it from the terminal:
groovy hello.groovy
Output:
Hello, Groovy Shell!
That’s it—you’ve successfully run your first Groovy shell script! 🎉
Writing Simple Automation Scripts
Groovy’s concise syntax and access to the full Java standard library make it perfect for everyday automation tasks. In this section, we’ll create small but powerful scripts to handle routine developer chores.
1. Automating File Operations
Suppose you want to list all files in a directory and print their sizes. In Groovy, this is just a few lines:
// listFiles.groovy
def dir = new File(".")
dir.eachFile { file ->
println "${file.name} - ${file.length()} bytes"
}
Run it:
groovy listFiles.groovy
Output example:
hello.groovy - 25 bytes
listFiles.groovy - 102 bytes
👉 With Groovy, working with files is straightforward—no need for verbose Java boilerplate.
2. Searching for Text in Files
Here’s a script that searches for a keyword in all .log
files inside a directory:
// searchLogs.groovy
def keyword = args ? args[0] : "ERROR"
new File(".").eachFileMatch(~/.*\.log/) { file ->
file.eachLine { line ->
if (line.contains(keyword)) {
println "${file.name}: $line"
}
}
}
Run with:
groovy searchLogs.groovy ERROR
This scans log files and highlights any line containing "ERROR"
.
3. Batch File Renaming
Need to rename files quickly? Let’s prepend today’s date to all .txt
files:
// renameFiles.groovy
def today = new Date().format("yyyyMMdd")
new File(".").eachFileMatch(~/.*\.txt/) { file ->
def newName = "${today}_${file.name}"
file.renameTo(new File(file.parent, newName))
println "Renamed ${file.name} -> ${newName}"
}
Run it:
groovy renameFiles.groovy
Now all .txt
files will be renamed with today’s date prefix.
4. Cleaning Up Temporary Files
Here’s a script to delete all .tmp
files in a project directory:
// cleanTmp.groovy
new File(".").eachFileRecurse { file ->
if (file.name.endsWith(".tmp")) {
println "Deleting ${file.path}"
file.delete()
}
}
Run it:
groovy cleanTmp.groovy
✅ With just a few lines of Groovy code, we’ve automated several file management tasks.
Working with Processes and System Commands
One of Groovy’s most useful features for scripting is its easy integration with system processes. You can run shell commands directly from your scripts and capture their output with very little code.
1. Running a Simple Command
Let’s run the ls
(Linux/macOS) or dir
(Windows) command to list files:
// runCommand.groovy
def command = "ls -l"
def process = command.execute()
process.in.eachLine { line ->
println line
}
Run it:
groovy runCommand.groovy
This will print the same output as ls -l
in your shell.
2. Capturing Command Output
Sometimes you want the result of a command for further processing. For example, counting running Java processes:
// countJava.groovy
def command = "ps -ef | grep java | grep -v grep"
def result = command.execute().text
def lines = result.readLines()
println "Java processes running: ${lines.size()}"
Output example:
Java processes running: 2
3. Passing Arguments to Commands
You can also pass arguments safely using a list instead of a string. This avoids shell parsing issues:
// pingHost.groovy
def host = args ? args[0] : "google.com"
def process = ["ping", "-c", "3", host].execute()
process.in.eachLine { println it }
Run it:
groovy pingHost.groovy github.com
4. Combining System Commands and File Operations
Imagine you want to compress a directory, then move the archive:
// backup.groovy
def dir = "logs"
def archive = "logs_backup.tar.gz"
// Run tar command
["tar", "-czf", archive, dir].execute().waitFor()
// Move to backup folder
def backupDir = new File("backup")
if (!backupDir.exists()) backupDir.mkdirs()
new File(archive).renameTo(new File(backupDir, archive))
println "Backup created at backup/${archive}"
Now you’ve automated backups with Groovy!
✅ At this point, you can see how Groovy makes it super easy to integrate system commands with scripting logic.
Working with JSON and XML
As developers, we often deal with configuration files, API responses, or logs in JSON and XML formats. Groovy makes parsing and generating these formats incredibly simple thanks to its built-in libraries.
1. Reading JSON
Groovy includes groovy.json.JsonSlurper
for parsing JSON.
// readJson.groovy
import groovy.json.JsonSlurper
def jsonText = '''
{
"name": "Alice",
"role": "Developer",
"skills": ["Groovy", "Java", "Spring Boot"]
}
'''
def slurper = new JsonSlurper()
def data = slurper.parseText(jsonText)
println "Name: ${data.name}"
println "Role: ${data.role}"
println "Skills: ${data.skills.join(', ')}"
Output:
Name: Alice
Role: Developer
Skills: Groovy, Java, Spring Boot
2. Writing JSON
Use groovy.json.JsonOutput
to generate JSON from Groovy maps or lists:
// writeJson.groovy
import groovy.json.JsonOutput
def person = [
name: "Bob",
role: "DevOps Engineer",
skills: ["Docker", "Kubernetes", "CI/CD"]
]
def json = JsonOutput.prettyPrint(JsonOutput.toJson(person))
println json
Output:
{
"name": "Bob",
"role": "DevOps Engineer",
"skills": [
"Docker",
"Kubernetes",
"CI/CD"
]
}
3. Parsing XML
For XML, Groovy provides XmlSlurper
:
// readXml.groovy
def xmlText = '''
<project>
<name>Demo App</name>
<version>1.0.0</version>
<dependencies>
<dependency>Groovy</dependency>
<dependency>Spring Boot</dependency>
</dependencies>
</project>
'''
def project = new XmlSlurper().parseText(xmlText)
println "Project: ${project.name}"
println "Version: ${project.version}"
println "Dependencies: ${project.dependencies.dependency*.text().join(', ')}"
Output:
Project: Demo App
Version: 1.0.0
Dependencies: Groovy, Spring Boot
4. Generating XML
Groovy also has MarkupBuilder
for creating XML programmatically:
// writeXml.groovy
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.person {
name "Charlie"
role "QA Engineer"
skills {
skill "Testing"
skill "Automation"
skill "Selenium"
}
}
println writer.toString()
Output:
<person>
<name>Charlie</name>
<role>QA Engineer</role>
<skills>
<skill>Testing</skill>
<skill>Automation</skill>
<skill>Selenium</skill>
</skills>
</person>
✅ With Groovy, JSON and XML handling is concise and intuitive, making it perfect for configuration automation or API integration.
HTTP Requests and APIs
Another everyday task for developers is interacting with web APIs—whether for fetching data, posting updates, or testing endpoints. Groovy makes HTTP requests simple with its built-in groovy.json
tools and the @Grab
dependency mechanism.
1. Simple HTTP GET Request
We can use URL
directly in Groovy to fetch data:
// httpGet.groovy
def url = "https://jsonplaceholder.typicode.com/posts/1"
def response = new URL(url).text
println response
Output:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit..."
}
2. Parsing JSON from an API
Let’s parse the response into Groovy objects using JsonSlurper
:
// parseApi.groovy
import groovy.json.JsonSlurper
def url = "https://jsonplaceholder.typicode.com/users/1"
def response = new URL(url).text
def json = new JsonSlurper().parseText(response)
println "Name: ${json.name}"
println "Email: ${json.email}"
println "Company: ${json.company.name}"
Output:
Name: Leanne Graham
Email: [email protected]
Company: Romaguera-Crona
3. Sending an HTTP POST Request
For more advanced HTTP operations, we can use HTTPBuilder (via @Grab
):
// httpPost.groovy
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
def client = new RESTClient("https://jsonplaceholder.typicode.com/")
def response = client.post(
path: "posts",
body: [title: "Groovy Post", body: "Hello API", userId: 1],
requestContentType: JSON
)
println "Status: ${response.status}"
println "Response: ${response.data}"
Output:
Status: 201
Response: [id: 101, title:Groovy Post, body:Hello API, userId:1]
4. Downloading a File via HTTP
Here’s a script to download a file from a URL:
// downloadFile.groovy
def url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
def file = new File("dummy.pdf")
file.withOutputStream { out ->
out << new URL(url).openStream()
}
println "Downloaded ${file.name} (${file.length()} bytes)"
✅ With just a few lines, Groovy can fetch APIs, parse JSON, send POST requests, and download files.
Useful Developer Utilities
Groovy scripts really shine when you combine multiple features—file handling, processes, and HTTP requests—into utilities that solve common developer problems. In this section, we’ll build practical scripts you can drop right into your toolkit.
1. Checking Environment Versions
Make sure the right tools are installed before working on a project:
// checkEnv.groovy
def tools = ["java -version", "groovy -v", "git --version", "docker --version"]
tools.each { cmd ->
try {
println "Running: $cmd"
def process = cmd.execute()
process.in.eachLine { println " $it" }
} catch (Exception e) {
println " ERROR: ${cmd.split(' ')[0]} not found"
}
println ""
}
Run it:
groovy checkEnv.groovy
This ensures your dev environment is ready.
2. Monitoring Logs for Errors
Tail a log file and highlight errors in real time:
// monitorLogs.groovy
def logFile = new File("app.log")
def lastSize = 0
while (true) {
if (logFile.length() > lastSize) {
logFile.withReader { reader ->
reader.skip(lastSize)
reader.eachLine { line ->
if (line.contains("ERROR")) {
println "[!] ${line}"
}
}
}
lastSize = logFile.length()
}
sleep(1000)
}
Run it:
groovy monitorLogs.groovy
Now you’ll get instant alerts for new error lines.
3. Project Scaffolding Script
Automate creating a new project folder structure:
// initProject.groovy
def projectName = args ? args[0] : "MyProject"
def baseDir = new File(projectName)
["src", "src/main", "src/test", "docs"].each {
def dir = new File(baseDir, it)
if (!dir.exists()) dir.mkdirs()
println "Created ${dir.path}"
}
new File(baseDir, "README.md").text = "# ${projectName}\n\nProject initialized with Groovy script."
println "Project ${projectName} initialized successfully!"
Run it:
groovy initProject.groovy AwesomeApp
4. Automating API Health Checks
Check if your services are up and running:
// healthCheck.groovy
import groovy.json.JsonSlurper
def urls = [
"https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/users/1"
]
urls.each { u ->
try {
def response = new URL(u).text
def json = new JsonSlurper().parseText(response)
println "[OK] ${u} - Response contains keys: ${json.keySet()}"
} catch (Exception e) {
println "[FAIL] ${u} - ${e.message}"
}
}
✅ With these utilities, Groovy becomes your Swiss army knife for development tasks—perfect for scripting in CI pipelines, automating local workflows, or enhancing productivity.
Conclusion + Next Steps
In this tutorial, we’ve explored how Groovy shell scripts can simplify and speed up everyday development tasks. From automating file operations, running system commands, handling JSON/XML, making HTTP requests, to building practical developer utilities, Groovy proves to be a flexible and powerful scripting language.
Key Takeaways:
-
Groovy is concise yet leverages the full Java ecosystem.
-
File and process automation are just a few lines of code.
-
JSON and XML parsing are built in and straightforward.
-
HTTP requests and API integration can be done without extra setup.
-
Practical utilities like environment checks, log monitoring, and project scaffolding can boost your productivity.
What’s Next?
If you enjoyed using Groovy for scripting, here are a few directions to explore:
-
🛠 Integrate Groovy scripts into CI/CD pipelines (e.g., Jenkins uses Groovy extensively).
-
📂 Build more advanced CLI tools by combining Groovy with libraries like
picocli
. -
🔗 Mix Groovy with Gradle tasks for project automation.
-
📚 Explore Groovy DSLs for writing more expressive scripts tailored to your workflow.
Groovy might not be the first tool you think of for scripting, but once you try it, you’ll see it’s an underrated powerhouse—especially for developers already comfortable with the JVM ecosystem.
So next time you reach for Bash or Python, give Groovy a chance. It might just become your new favorite scripting tool! 🚀
You can get the full source code on our GitHub.
That's just the basics. If you need more deep learning about Groovy and Grails, you can take the following cheap course:
- Mastering Grails. A Comprehensive Grails Course.
- Intro to web programming with Groovy on Grails
- Groovy Programming Fundamentals for Java Developers
- The Complete Apache Groovy Developer Course
- Groovy Fundamentals For Testers - Step By Step
- Webservice Automation using SoapUI Groovy and Maven
Thanks!