groovysh, the interactive shell
groovysh is the interactive shell of the language: it reads a line, evaluates it, prints the result, and keeps the variables of the lines before it. It is a REPL, which is the fastest way to check what a method returns without writing a file.
A shell wants a terminal, and this container has none, so the session below is fed through a pipe. The prompt groovy> and the results are exactly what the shell prints; the colour codes of a terminal are left out.
printf 'println 6 * 7\n/exit\n' | groovysh
Groovy Shell (5.0.8, JVM: 21.0.13.1, Term: dumb)
Type '/help' or '/h' for help, '/exit' or '/x' to exit.
groovy> println 6 * 7
42
groovy> /exit
The first two lines are the banner: the version, the JVM, and the two commands of the help line. The ASCII art below them is the logo of the shell. The session ends with /exit.
The steps of a session
- Type groovysh. The prompt groovy> appears.
- Type an expression: 1 + 2. The shell prints 3 on the next line.
- Type a variable: def n = 5. The next line can use it: n * n prints 25.
- Type /help for the command list, /exit to leave.
A command starts with a slash because a bare word would be evaluated as Groovy, and the older colon spelling still works: /load file.groovy (or :load) runs a script inside the session and keeps its variables, and /help (or :help) lists the commands.
A method and a class
The shell accepts a method definition and a class, and both stay defined for the rest of the session:
printf 'def twice(int n) { n * 2 }\nprintln twice(21)\nclass Point { int x; int y }\nprintln new Point(x: 1, y: 2)\n/exit\n' | groovysh
groovy> def twice(int n) { n * 2 }
groovy> println twice(21)
42
groovy> class Point { int x; int y }
groovy> println new Point(x: 1, y: 2)
Point@39f5b723
The last line is the default toString of the class: the name and a hash code, which changes on every run. The AST transforms lesson replaces it with a real one.
What the shell is not
- Not a script. Nothing is saved: a session that matters ends in a file, which is what groovyc compiles.
- Not a debugger. It evaluates expressions; a breakpoint needs a debugger and a program that waits for one.
- Not a terminal program here. A container without a TTY can pipe into it, as above, but the arrow keys, history and completion need a real terminal.
Related
- The first script and groovy -e: the file and the one-liner that replace a session.
- Strings and GStrings: the first thing to try at the prompt.
Автор статьи: Arthur Isaev