tags:

views:

171

answers:

2

I'm writing a groovy script that I want to be controlled via a properties file stored in the same folder. However, I want to be able to call this script from anywhere. When I run the script it always looks for the properties file based on where it is run from, not where the script is.

How can I access the path of the script file from within the script?

+3  A: 

Interesting question. You are correct that the first thing I tried, File(".").getCanonicalPath(), does not work; it returns the running directory.

doesntWork = new File(".").getCanonicalPath()
println doesntWork

I did a little research and here's how to do it, depending on whether you want the directory, or the script itself:

scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
scriptFile = getClass().protectionDomain.codeSource.location.path

println scriptDir
println scriptFile
seansand
Interesting. It doesn't work the way I expected it to. But that is due to the fact I am running a gant script from gant. So the codeSource is actually where gant is, not where my script is.
Dan Woodward
+1  A: 

This makes sense if you are running the Groovy code as a script, otherwise the whole idea gets a little confusing, IMO. The workaround is here: http://jira.codehaus.org/browse/GROOVY-1642

Basically this involves changing startGroovy.sh to pass in the location of the Groovy script as an environment variable.

Joshua Davis