How do I get the name of the script being executed in Groovy?
It is not a command line argument and hence the args array is not of any help.
How do I get the name of the script being executed in Groovy?
It is not a command line argument and hence the args array is not of any help.
The above solutions are perfect if applied in the script itself. Sometimes it is needed to know script name from other files or classes called from the script.
E.g. the script script1.groovy calls SomeClass. This SomeClass also can find the name of the script. One-line solution is
StackTraceUtils.deepSanitize(new Exception()).getStackTrace().last().getFileName()
Look at the following example:
script1.groovy:
import SomeClass
def someInst = new SomeClass()
SomeClass.groovy:
import org.codehaus.groovy.runtime.StackTraceUtils
class SomeClass {
String scriptName = StackTraceUtils.deepSanitize(new Exception()).getStackTrace().last().getFileName().replaceAll(/\.groovy/, '')
println "My calling script is '$scriptName'"
}
output:
My calling script is 'script1'