Groovy as a Scripting Language
Groovy scripts run directly with the groovy command-line launcher (no explicit class or public static void main required), compiling to JVM bytecode on the fly, which makes Groovy a practical alternative to Bash or Python for automation tasks that need access to the full Java ecosystem — file APIs, HTTP clients, database drivers — while keeping the terse, dynamically-typed feel of a scripting language.
Cricket analogy: Much like a franchise can field a T10 exhibition team without the full ceremony of a Test match squad announcement, a Groovy script runs with the groovy launcher without needing a formal class declaration or main method, cutting straight to the action.
File I/O and Text Processing
Groovy adds convenience methods directly onto java.io.File through its GDK (Groovy Development Kit) extensions, so reading a file is new File('data.txt').text, iterating lines is new File('log.txt').eachLine { line -> ... }, and writing is new File('out.txt').text = 'content' or << for appending — these replace multi-line Java BufferedReader/FileWriter boilerplate with one-line idiomatic calls that still operate on real java.io.File objects underneath.
Cricket analogy: Much like a modern scoring app lets a scorer tap one button to log a boundary instead of filling out a manual scorecard entry, Groovy's new File('data.txt').text reads an entire file in one call instead of manual BufferedReader boilerplate.
Running External Processes
Groovy extends String with an .execute() method that spawns an external process, returning a Process object you can interrogate with .text to capture stdout, or pipe together using the | operator like ('ps aux' | 'grep java') to chain processes the way you would in a shell pipeline, and waitForProcessOutput() or waitFor() lets a script block until the external command finishes and check .exitValue().
Cricket analogy: Much like a captain relays instructions to the wicketkeeper who relays them to the bowler in a coordinated chain, Groovy's ('ps aux' | 'grep java') chains one process's output into another's input, mirroring a shell pipeline.
#!/usr/bin/env groovy
import groovy.cli.picocli.CliBuilder
def cli = new CliBuilder(usage: 'cleanup.groovy -d <dir> [-v]')
cli.d(longOpt: 'dir', args: 1, required: true, 'directory to clean up')
cli.v(longOpt: 'verbose', 'enable verbose output')
def options = cli.parse(args)
if (!options) System.exit(1)
def targetDir = new File(options.d)
def verbose = options.v
try {
targetDir.eachFileRecurse { file ->
if (file.name.endsWith('.tmp')) {
if (verbose) println "Deleting ${file.path}"
file.delete()
}
}
def result = "du -sh ${targetDir.path}".execute()
println result.text.trim()
} catch (IOException e) {
System.err.println "Cleanup failed: ${e.message}"
System.exit(1)
}Command-Line Argument Parsing and Error Handling
Groovy scripts receive command-line arguments through the implicit args array, and for anything beyond a couple of flags, groovy.cli.picocli.CliBuilder (or the older commons-cli-based CliBuilder) lets you declare options like cli.v(longOpt: 'verbose', 'enable verbose output') and parse them with def options = cli.parse(args), while wrapping filesystem or process calls in try/catch blocks around IOException is essential since automation scripts often run unattended and need to fail loudly (non-zero exit code via System.exit(1)) rather than silently.
Cricket analogy: Much like a bowling review request must be filed within a strict time window or it's automatically rejected, a Groovy automation script wrapped in try/catch should fail fast with System.exit(1) rather than silently continuing after an IOException.
Groovy scripts can be made directly executable on Linux/macOS by adding a #!/usr/bin/env groovy shebang line and running chmod +x script.groovy, letting you invoke ./script.groovy exactly like a Bash script while still running on the JVM.
- Groovy scripts run directly via the
groovylauncher with no explicit class or main method required. - GDK extensions add convenience methods to java.io.File, like
.text,.eachLine { }, and<<for appending. - String.execute() spawns an external process; the
|operator chains processes like a shell pipeline. - waitForProcessOutput() / waitFor() and .exitValue() let a script synchronize with and check external commands.
- CliBuilder (picocli-based) declares named command-line options instead of manually indexing the args array.
- Automation scripts should catch IOException and other failures explicitly and exit non-zero via System.exit(1).
- A shebang line (#!/usr/bin/env groovy) plus chmod +x makes a Groovy script directly executable like a shell script.
Practice what you learned
1. How do you run a Groovy script without defining a class or main method?
2. Which GDK extension reads an entire file's contents in one line?
3. What does String.execute() do in Groovy?
4. What is CliBuilder used for in Groovy scripts?
5. Why should an unattended automation script call System.exit(1) on failure?
Was this page helpful?
You May Also Like
Groovy and Jenkins Pipelines
Understand how Jenkins Pipeline uses Groovy for both Declarative and Scripted syntax, including shared libraries and CPS constraints.
XML and JSON with Groovy
Learn Groovy's built-in support for parsing and building XML and JSON using XmlSlurper, XmlParser, MarkupBuilder, JsonSlurper, and JsonOutput.
Groovy and Gradle
Learn how Gradle uses Groovy as its build-script DSL, covering tasks, dependencies, plugins, and multi-project builds.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics