1

I'm looking for a way to have groovysh initialized and then dropped into a regular groovysh interactive session. That is:

  • Run some scripts (e.g. imports or anything else)
  • Continue running in groovysh as if previous script was typed manually from the start of the session.

Seen this:

but I'd like to be able to do this on a per-application, not per-user level. I.e. different applications usually do not import same things (or initialize in the same way otherwise). Is that possible?

Community
  • 1
  • 1
steady rain
  • 2,246
  • 3
  • 14
  • 18

3 Answers3

1

Since Groovy 2.4 you can use groovysh -e '... your code here ...'.

Examples:

$ groovysh -e '2+2'
Groovy Shell (2.4.7, JVM: 1.8.0_131)
Type ':help' or ':h' for help.
----------------------------------------------------------
groovy:000> 2+2
===> 4

If you want to preload a script, use :load like so:

$ cat preamble.groovy 
def hello(x) {
  "Hello ${x}"
}
println hello("world")

$ groovysh -e ':load preamble.groovy'
Groovy Shell (2.4.7, JVM: 1.8.0_131)
Type ':help' or ':h' for help.
----------------------------------------------------------
groovy:000> :load preamble.groovy
===> true
Hello world
===> null
groovy:000> hello('stackoverflow')
===> Hello stackoverflow

(in last example I manually typed last line, I could use function hello defined in preamble)

qlown
  • 527
  • 3
  • 8
0

Per this post:

looks like Groovy <= 2.3 doesn't support this and it's going to be present in Groovy 2.4 using this syntax:

groovysh -e foo.groovy
steady rain
  • 2,246
  • 3
  • 14
  • 18
  • Actually it's `groovysh -e ' ... your code here ...'`, so for example `groovysh -e '2+2'`. Unfortunately `groovysh -e 'load "foo.groovy"'` does not work :( – qlown Jun 14 '17 at 21:30
0

Using the load keyword seems to work:

$ cat test.groovy
myStr = "hello World!"
$
$ groovysh
groovy:000> load test.groovy
===> hello World!
groovy:000> println myStr
hello World!
===> null
groovy:000>
kmad1729
  • 1,484
  • 1
  • 16
  • 20