Running Groovy script from the command line

UnixGroovy

Unix Problem Overview


When I did which groovy, I got the below output:

/usr/local/bin/groovy

So I went ahead and created a helloworld.groovy with the below content

#!/usr/local/bin/groovy
println "hello world"

After that I did chmod +x helloworld.groovy and attempted to run the file with ./hellworld.groovy and sadly, I got this error ./helloworld.groovy: line 2: print: command not found

I could get rid of the error by changing to

#!/usr/bin/env groovy
println "hello world"

Why would the first method cause the error?

Unix Solutions


Solution 1 - Unix

You need to run the script like this:

groovy helloworld.groovy

Solution 2 - Unix

#!groovy
println("hello world!")
$ chmod +x script.groovy
$ ./script.groovy

Solution 3 - Unix

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

Solution 4 - Unix

#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;

println("hello");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjjenniferView Question on Stackoverflow
Solution 1 - UnixgrantmcconnaugheyView Answer on Stackoverflow
Solution 2 - UnixSP QRTView Answer on Stackoverflow
Solution 3 - UnixChris DukesView Answer on Stackoverflow
Solution 4 - UnixdieterView Answer on Stackoverflow