Input and Command-Line Arguments
Prerequisites: Methods
Command-line arguments
Arguments after the script name arrive in the args array:
// illustrative — run as: groovy greet.groovy Ada 3
def name = args ? args[0] : 'world'
def times = args.size() > 1 ? args[1].toInteger() : 1
times.times { println "Hello, $name!" }
Hello, Ada!
Hello, Ada!
Hello, Ada!
args is a String[]; convert numbers yourself with toInteger() or
toBigDecimal(). An empty array is falsy, so args ? ... : ... gives a
default when nothing was passed.
Reading from the keyboard
// illustrative — needs keyboard input
def reader = System.in.newReader()
print 'What is your name? '
def name = reader.readLine()
print 'How old are you? '
def input = reader.readLine()
if (input?.isInteger()) {
println "Hi $name, next year you'll be ${input.toInteger() + 1}."
} else {
println "Sorry, '$input' isn't a number."
}
What is your name? Ada
How old are you? 36
Hi Ada, next year you'll be 37.
readLine() returns null at the end of input (for example when input
is piped from a file), so check with ?. before using it.
Reading piped input
// illustrative — run as: type data.txt | groovy count.groovy
def lines = System.in.readLines()
println "${lines.size()} lines, ${lines.sum { it.tokenize().size() }} words"
Environment variables and exit codes
def home = System.getenv('HOME') ?: System.getenv('USERPROFILE')
println home != null
def mode = System.getenv('APP_MODE') ?: 'development'
println "mode: $mode"
true
mode: development
Call System.exit(1) to end a script with an error code that shells and
CI systems can detect. Level 3 shows CliBuilder for real command-line
options like --verbose.