Learn the Groovy command line -e option with 10 practical examples. Run Groovy scripts instantly without creating files. Tested on Groovy 5.x.
“Why create a file when you can run it right from the command line?”
Brian Kernighan, Unix Philosophy
Last Updated: March 2026 | Tested on: Groovy 5.x, Java 17+ | Difficulty: Beginner | Reading Time: 10 minutes
Sometimes you just want to test a quick idea – check a date format, do a math calculation, or parse a small JSON string. Creating a file for a one-liner feels like overkill. The groovy command line -e option lets you run code directly from your terminal without creating any file at all.
The groovy -e flag lets you run Groovy code directly from your terminal – no file needed. It’s fast, it’s convenient, and once you start using it, you’ll wonder how you lived without it.
If you’re new to Groovy, make sure you’ve got it installed first. Our Groovy Hello World guide covers installation in detail.
Table of Contents
What is the Groovy -e Option?
The -e flag tells the Groovy runtime to evaluate the given string as Groovy code. Instead of pointing to a file, you pass the code directly as a command-line argument.
According to the official Groovy documentation, the -e option is part of the groovy command’s evaluation mode – it compiles and executes the code string in a single step.
Key Points:
- No file creation needed – code runs directly from the terminal
- Full access to all Groovy features – closures, GStrings, collections, GDK methods
- Can import classes, use multi-line code (with proper escaping), and pass arguments
- Perfect for quick tests, one-liners, and shell scripting
- Works on Linux, Mac, and Windows command prompts
Why Use Groovy -e?
There are several situations where groovy -e beats creating a script file:
- Quick calculations: Math, date formatting, string manipulation
- System checks: JVM version, environment variables, classpath
- Data conversion: JSON parsing, Base64 encoding, URL encoding
- Shell scripting: Use Groovy one-liners inside bash scripts
- Learning: Quickly test syntax without IDE overhead
Think of it as a REPL for one-liners. If you need more than a few lines, switch to a script file or the Groovy Console.
Syntax and Basic Usage
Basic Syntax
Groovy -e Syntax
groovy -e "your groovy code here"
Common Groovy Command Line Options
| Option | Description | Example |
|---|---|---|
-e | Evaluate code string | groovy -e "println 'hi'" |
-l | Auto-print each line of input | groovy -l -e "line.toUpperCase()" |
-n | Process stdin line by line | echo "hello" | groovy -n -e "println line" |
-p | Like -n but auto-prints result | echo "hello" | groovy -p -e "line.toUpperCase()" |
-i | In-place edit (with -n or -p) | Modifies file directly |
10 Practical Examples
Example 1: Hello World One-Liner
What we’re doing: The simplest possible groovy -e command.
Example 1: Hello World
groovy -e "println 'Hello, World!'"
Output
Hello, World!
What happened here: Groovy compiled and executed the string in one step. No file, no class – just instant output. Notice the single quotes inside double quotes to avoid shell escaping issues.
Example 2: Check System Information
What we’re doing: Printing JVM and Groovy version info from the command line.
Example 2: System Info
groovy -e "println 'Groovy: ' + GroovySystem.version; println 'Java: ' + System.getProperty('java.version'); println 'OS: ' + System.getProperty('os.name')"
Output
Groovy: 5.0.0 Java: 17.0.x OS: Windows 10
What happened here: We used semicolons to separate multiple statements on one line. This is a quick way to verify your Groovy environment without opening an IDE.
Example 3: Quick Math Calculations
What we’re doing: Using Groovy as a powerful calculator from the terminal.
Example 3: Quick Math
groovy -e "println 2 ** 10" groovy -e "println Math.sqrt(144)" groovy -e "println (1..100).sum()" groovy -e "println 0.1 + 0.2"
Output
1024 12.0 5050 0.3
What happened here: Groovy handles power operator (**), Java’s Math library, range sums, and – notice – 0.1 + 0.2 gives 0.3 (not 0.30000000000000004 like in most languages). That’s because Groovy uses BigDecimal by default for decimal arithmetic.
Pro Tip: Groovy’s BigDecimal default means you can trust decimal math from the command line – no floating-point surprises.
Example 4: Date and Time Operations
What we’re doing: Getting the current date and time, formatted.
Example 4: Date and Time
groovy -e "println new Date()"
groovy -e "println new Date().format('yyyy-MM-dd HH:mm:ss')"
groovy -e "println 'Day of week: ' + new Date().format('EEEE')"
Output
Sat Mar 08 14:30:45 IST 2026 2026-03-08 14:30:45 Day of week: Saturday
What happened here: Groovy adds a format() method to Java’s Date class through the GDK. No need to manually create SimpleDateFormat – just call format() with a pattern. Super handy when you need a quick timestamp.
Example 5: JSON Parsing
What we’re doing: Parsing a JSON string directly from the command line.
Example 5: JSON Parsing
groovy -e "import groovy.json.JsonSlurper; def json = new JsonSlurper().parseText('{\"name\":\"Alice\",\"age\":30}'); println json.name; println json.age"
Output
Alice 30
What happened here: We imported JsonSlurper, parsed a JSON string, and accessed properties with dot notation. You need to escape the double quotes inside JSON with backslashes when using double-quoted shell strings.
Example 6: Base64 Encoding and Decoding
What we’re doing: Quick Base64 encode/decode from the terminal.
Example 6: Base64
groovy -e "println 'Hello World'.bytes.encodeBase64()"
groovy -e "println new String('SGVsbG8gV29ybGQ='.decodeBase64())"
Output
SGVsbG8gV29ybGQ= Hello World
What happened here: Groovy’s GDK adds encodeBase64() to byte arrays and decodeBase64() to strings. This is faster than searching for online Base64 tools and doesn’t send your data to a third party.
Example 7: Generate a UUID
What we’re doing: Generating unique identifiers on the fly.
Example 7: UUID Generation
groovy -e "println UUID.randomUUID()"
groovy -e "3.times { println UUID.randomUUID() }"
Output
a4f7c2b1-3d5e-4f8a-9c1b-2d3e4f5a6b7c f1e2d3c4-b5a6-7890-1234-567890abcdef a1b2c3d4-e5f6-7890-abcd-ef1234567890 98765432-10fe-dcba-9876-543210fedcba
What happened here: Java’s UUID class is available directly – no imports needed for java.util classes. Combined with times(), you can generate multiple UUIDs in one command.
Example 8: File Operations
What we’re doing: Reading and writing files from a one-liner.
Example 8: File One-Liners
groovy -e "new File('test.txt').text = 'Hello from Groovy -e!'"
groovy -e "println new File('test.txt').text"
groovy -e "println new File('.').listFiles()*.name"
Output
Hello from Groovy -e! [test.txt, hello.groovy, build.gradle]
What happened here: File read/write in one line each. The *.name is Groovy’s spread operator – it calls .name on every element in the list. Want to learn more about file operations? Check our print vs println guide for output basics.
Example 9: Working with Collections
What we’re doing: List and map operations from the command line.
Example 9: Collections
groovy -e "println [5,3,8,1,9,2].sort()"
groovy -e "println [1,2,2,3,3,3,4].unique()"
groovy -e "println [1,2,3,4,5].collect { it * it }"
groovy -e "println [10,20,30,40,50].findAll { it > 25 }"
Output
[1, 2, 3, 5, 8, 9] [1, 2, 3, 4] [1, 4, 9, 16, 25] [30, 40, 50]
What happened here: All of Groovy’s powerful collection methods – sort(), unique(), collect(), findAll() – work perfectly in -e mode. Great for quick data manipulation without writing scripts.
Example 10: URL Content and HTTP Requests
What we’re doing: Fetching content from a URL directly from the terminal.
Example 10: URL Fetch
groovy -e "println 'https://api.github.com'.toURL().text.take(200)"
Output
{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authori
What happened here: Groovy adds a toURL() method to strings and a text property to URL objects. One line fetches the full response. The take(200) limits output to the first 200 characters so your terminal doesn’t get flooded.
Pro Tip: Combine this with
JsonSlurperto parse API responses in a single line:groovy -e "println new groovy.json.JsonSlurper().parse('https://api.github.com'.toURL()).current_user_url"
Advanced Command Line Options
Process stdin with -n and -p
The -n and -p options let you process piped input line by line – similar to awk or sed:
Processing stdin
# -n: process each line (you handle printing) echo -e "hello\nworld\ngroovy" | groovy -n -e "println line.toUpperCase()" # -p: process each line (auto-prints the result) echo -e "hello\nworld\ngroovy" | groovy -p -e "line.toUpperCase()"
Output
HELLO WORLD GROOVY
Pass Arguments to -e Scripts
Passing Arguments
groovy -e "println 'Hello, ' + args[0] + '!'" Alice
groovy -e "args.each { println it }" one two three
Output
Hello, Alice! one two three
Arguments after the code string are accessible via the args array, just like in a regular Groovy script.
Multi-Statement One-Liners
Multi-Statement
groovy -e "def x = 10; def y = 20; println 'Sum: ' + (x + y); println 'Product: ' + (x * y)"
Output
Sum: 30 Product: 200
Use semicolons to separate multiple statements in a single -e string.
Edge Cases and Best Practices
Quote Escaping on Different Platforms
Platform Quote Handling
# Linux/Mac - use single quotes for the outer string groovy -e 'println "Hello, World!"' # Windows CMD - use double quotes, escape inner quotes groovy -e "println 'Hello, World!'" # Windows PowerShell - single quotes or backtick escape groovy -e "println 'Hello, World!'"
Best Practices
DO:
- Use
groovy -efor quick experiments and one-liners - Use single quotes inside double-quoted shell strings to avoid escaping
- Use semicolons to separate multiple statements
- Switch to a script file when your one-liner exceeds ~100 characters
DON’T:
- Write complex multi-class programs in a single
-estring - Forget to escape special characters in your shell
- Use
-efor production scripts – use proper.groovyfiles instead
Common Pitfalls
Pitfall 1: Quote Conflicts
Problem: Shell interprets your quotes before Groovy sees them.
Wrong Way
# This fails on Linux/Mac - shell interprets the double quotes groovy -e "println "Hello""
Solution:
Correct Way
# Use single quotes inside double quotes groovy -e "println 'Hello'" # Or on Linux/Mac, use single quotes outside groovy -e 'println "Hello"'
Pitfall 2: Dollar Signs in Bash
Problem: Bash interprets $ as variable expansion before Groovy sees it.
Wrong Way
# Bash tries to expand ${name} as a shell variable
groovy -e "def name = 'World'; println \"Hello, ${name}!\""
Solution:
Correct Way
# Use single quotes for the outer string (no bash expansion)
groovy -e 'def name = "World"; println "Hello, ${name}!"'
Output
Hello, World!
Conclusion
The Groovy -e command line option is one of those tools that seems small but saves you time every day. Need to check a date format? groovy -e. Quick Base64 decode? groovy -e. Parse a JSON response? You get the idea.
It turns your terminal into a Groovy playground. And because Groovy has access to all Java libraries plus its own GDK enhancements, there’s very little you can’t do in a one-liner.
Next time you reach for a calculator, a Base64 website, or an online JSON formatter – try groovy -e instead. You might never go back.
Summary
groovy -e "code"runs Groovy code without creating a file- Use semicolons to separate multiple statements in one-liners
- Watch out for shell quote conflicts – use single quotes inside double quotes
- The
-nand-pflags process piped input line by line - Arguments after the code string are accessible via
args[]
If you also work with build tools, CI/CD pipelines, or cloud CLIs, check out Command Playground to practice 105+ CLI tools directly in your browser — no install needed.
Up next: Groovy String Tutorial – The Complete Guide
Frequently Asked Questions
How do I run Groovy from the command line?
Use groovy -e "your code" to run code directly, or groovy filename.groovy to run a script file. Make sure Groovy is installed and in your system PATH. Verify with groovy --version.
What does the -e flag do in Groovy?
The -e flag tells the Groovy runtime to evaluate the following string as Groovy code. It compiles and executes the code in a single step without needing a script file. Example: groovy -e "println 'Hello'".
Can I use Groovy -e for multi-line code?
Yes, separate statements with semicolons: groovy -e "def x = 10; def y = 20; println x + y". On Linux/Mac, you can also use $’\n’ for actual newlines. For anything complex, a script file is more maintainable.
How do I pass arguments to groovy -e?
Place arguments after the code string: groovy -e "println args[0]" hello. Arguments are accessible via the args array, just like in regular Groovy scripts. Multiple arguments are space-separated.
Does groovy -e support imports?
Yes, you can include import statements in the -e string: groovy -e "import groovy.json.JsonSlurper; println new JsonSlurper().parseText('{\"a\":1}')". Standard Java classes like Date, List, and Map are auto-imported.
Related Posts
Previous in Series: Groovy Def Keyword – Dynamic Typing Explained
Next in Series: Groovy String Tutorial – The Complete Guide
Related Topics You Might Like:
- Groovy Hello World – Your First Groovy Program
- Groovy print vs println – Output Methods
- Groovy File Operations – Read, Write, Delete
This post is part of the Groovy & Grails Cookbook series on TechnoScripts.com

No comment