5

Given the following directory structure:

/home/some/random/foler/myScript.grooy

... how can I programmatically obtain the path to myScript.grooy parent directory right in the script itself?

Ultimately I'm trying to read in several files from the same directory the script is in.

EDIT: trying to run it on Windows 7, Groovy 2.0.1, groovy console

vector
  • 7,334
  • 8
  • 52
  • 80
  • 2
    possible duplicate of [How do you get the path of the running script in groovy?](http://stackoverflow.com/questions/1163093/how-do-you-get-the-path-of-the-running-script-in-groovy) – tim_yates Aug 14 '12 at 18:52
  • Does this answer your question? [How do you get the path of the running script in groovy?](https://stackoverflow.com/questions/1163093/how-do-you-get-the-path-of-the-running-script-in-groovy) – M. Justin Dec 24 '21 at 08:49

1 Answers1

18

Well, the solution is in Java's File class:

println new File(".").absolutePath

If you want to obtain every groovy script in the same directory, maybe you could use some of other facilities in the Groovy JDK, like eachFile:

def files = []
new File(".").eachFile { 
    if (it.name.endsWith(".groovy") ) files << it 
}
println files

If you want the running script name, well, you've got a problem (https://issues.apache.org/jira/browse/GROOVY-1642)

Accordingly to that JIRA, this is the current workaround (which doesn't always work):

URL scriptUrl = getClass().classLoader.resourceLoader
    .loadGroovySource(getClass().name)
Lifeweaver
  • 986
  • 8
  • 29
Will
  • 14,348
  • 1
  • 42
  • 44
  • ... hm, File(".").absolutePath gives me "C:\Users\userNameHere\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Groovy\." and workaround does not work either, bummer :-( – vector Aug 14 '12 at 18:44
  • Aren't you running groovy through cmd? – Will Aug 14 '12 at 18:53
  • goovy console, would that make a difference? – vector Aug 14 '12 at 19:08
  • I run it through my shell, and not groovyconsole, maybe that is the problem: it ends up getting the path to groovyconsole instead of the script – Will Aug 15 '12 at 11:51