问题
Is it possible to declare at the start of a file that it should be executed as a Groovy script?
Examples for other scripting languages:
#!/bin/sh
#!/usr/bin/python
#!/usr/bin/perl
回答1:
This one #!/usr/bin/env groovy
will search your path looking for groovy to execute the script
回答2:
According to this you can use #!/usr/bin/groovy
(if that's its location). The search term you are looking for is shebang
(which is what that first line is called).
回答3:
A common trick is to write a script that has meaning in more than one language, also known as a "polyglot" script.
In the case of Bash and Groovy, this is particularly easy:
#!/bin/sh
//bin/true; exec groovy -cp .. "$0"
println "Hello from Groovy"
- The first line is a shebang (
#!
) that tells the OS to run the script as a regular shell script. - The second line, when executed by the shell, invokes the
/bin/true
command (a no-op); then finds the groovy executable in the PATH and runs it on the script file itself ("$0"
) plus additional arguments, replacing the current shell process (exec
) - Groovy will ignore the first line, because it's a shebang; it will ignore the second line because it's a comment (
//
) and will run the rest of the script.
If you need a more elaborate shell part, maybe to set up environment variables, or discover where Groovy is installed, you can use a different trick:
#!/bin/sh
'''':
echo Hello from Shell
exec groovy -cp .. "$0"
'''
println "Hello from Groovy"
- Again, the shebang signals the OS to start executing this files as a shell script.
- The shell parses
'''':
as two empty strings''
followed by a colon, which is a no-op. - The shell will execute the rest of the file, line by line, until it find an
exec
or anexit
- If everything is ok, the shell will run the Groovy command on the script file itself (
"$0"
) - Groovy will skip the shebang line, then it will parse
'''':
as the beginning of a long string'''
, thus skipping all the shell commands, and then run the rest of the script.
来源:https://stackoverflow.com/questions/5479731/shebang-and-groovy