10 Useful Groovy -e Command Line Examples to Run Scripts Instantly

You want to check what a regex matches, or how Groovy formats today’s date, and opening an IDE for that feels ridiculous. The groovy command line -e option runs a snippet straight from your terminal, no file required. This post covers the syntax, 10 tested one-liners, and the -n and -p flags that turn Groovy into a text-processing tool.

“Why create a file when you can run it right from the command line?”

Last Updated: July 2026 | Tested on: Groovy 5.0.6, 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.

The diagram below shows the full path your one-liner takes: the shell strips the outer quotes, Groovy compiles your code once, and then the mode flag you pick (plain, -n, or -p) decides whether the code runs a single time or loops over each line of stdin and whether the result is printed for you:

plain -e-n with -e-p with -eYou type: groovy [flag] -e‘code’ [args]Shell strips outer quotesand splits argumentsGroovy compiles the -estring onceWhich mode flag?Run code one timeargs available as args arrayRead stdin, loop per lineline holds current textyou call println yourselfRead stdin, loop per lineauto print the last valueResult printed to terminalGroovy -e Execution Flow: Shell Parsing to Runtime Mode

Tip: click the diagram to open it full screen, then use the zoom and pan controls for a closer look.

If you’re new to Groovy, make sure you’ve got it installed first. Our Groovy Hello World guide covers installation in detail.

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

OptionDescriptionExample
-eEvaluate code stringgroovy -e "println 'hi'"
-lAuto-print each line of inputgroovy -l -e "line.toUpperCase()"
-nProcess stdin line by lineecho "hello" | groovy -n -e "println line"
-pLike -n but auto-prints resultecho "hello" | groovy -p -e "line.toUpperCase()"
-iIn-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 JsonSlurper to 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 -e for 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 -e string
  • Forget to escape special characters in your shell
  • Use -e for production scripts – use proper .groovy files 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.

The groovy command line turns your terminal into a 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 -n and -p flags 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.

Interview Questions on the Groovy Command Line

“These come from real screens. Practice answering before you read each answer.”

Q: A one-liner with groovy -e "println \"${JAVA_HOME}\"" prints your JDK path on Linux, but the same idea with a Groovy variable prints an empty string. Which layer is interpolating, and how do you control it?

There are two interpolation layers stacked: the shell and Groovy, and both use dollar syntax. Inside double quotes, bash expands ${...} before Groovy ever runs, so a shell variable works and a Groovy variable becomes empty text. Wrap the code in single quotes and the shell passes it through untouched, letting Groovy’s GString do the work. The gotcha to volunteer: on Windows cmd it is roughly reversed, since cmd uses percent syntax and you quote the outer string with double quotes there.

Q: You have a 2 GB application log and need to pull out just the lines with a 500 status, uppercased. Can Groovy do that from the command line without loading the file into memory?

Yes, that is exactly what the -n and -p flags exist for. Pipe the file in and Groovy runs the -e code once per input line, streaming, with the current line bound to the line variable, so memory stays flat regardless of file size. With -n you decide what to print yourself, which suits filtering; with -p the value of the last expression is printed automatically, which suits transformations. It is the awk and sed niche, except you get the whole JDK in the loop body.

Q: A Jenkins job calls groovy -e inside a shell loop, once per file, and the stage takes twenty minutes for a few hundred files. Why so slow, and what is the fix?

Every invocation pays the fixed costs again: JVM startup plus compiling the snippet to bytecode. That is a second or more each time, multiplied by hundreds of files, and it dwarfs the actual work. The fix is to invert the loop: run one Groovy process that iterates the files itself, either a small script file or a single -e body using new File(dir).eachFile. Same logic, one JVM, one compile. Generalizing, groovy -e is for interactive one-offs; anything repeated belongs inside one process.

Q: Your one-liner needs a library that is not in the JDK, say a YAML parser, on a box that has only Groovy installed. What are your options?

Two realistic ones. If the jar already exists on the machine, pass it with -cp so the snippet can import it. If not, put a @Grab annotation in the -e string and Grape resolves the dependency from Maven Central into its local cache before running. The caveats an interviewer wants to hear: @Grab needs network access the first time, corporate proxies and locked-down agents often block it, and resolution time makes it a poor fit for anything that runs frequently. For production automation, a proper build with declared dependencies wins.

Previous in Series: Groovy Def Keyword – Dynamic Typing Explained

Next in Series: Groovy String Tutorial – The Complete Guide

Related Topics You Might Like:

This post is part of the Groovy & Grails Cookbook series on TechnoScripts.com

RahulAuthor posts

Avatar for Rahul

Rahul is a passionate IT professional who loves to sharing his knowledge with others and inspiring them to expand their technical knowledge. Rahul's current objective is to write informative and easy-to-understand articles to help people avoid day-to-day technical issues altogether. Follow Rahul's blog to stay informed on the latest trends in IT and gain insights into how to tackle complex technical issues. Whether you're a beginner or an expert in the field, Rahul's articles are sure to leave you feeling inspired and informed.

No comment

Leave a Reply

Your email address will not be published. Required fields are marked *