kscript : How to get directory of current file?

1k Views Asked by At

Is there a way to get directory of a current script location in kotlin script?

I could achieve this in bash with

 dirname $0

or

# Absolute path to this script. /home/user/bin/foo.sh
SCRIPT=$(readlink -f $0)
# Absolute path this script is in. /home/user/bin
SCRIPTPATH=`dirname $SCRIPT`
2

There are 2 best solutions below

3
On

You can use:

File(".")

and don't forget to import java.io.File

0
On

The builtin kotlin-main-kts script definition adds a __FILE__ variable to the script context. Access works just as you'd expect:

println(__FILE__) // java.io.File object representing /home/user/bin/foo.main.kts (or wherever the script is)
println(__FILE__.parentFile) // java.io.File object representing /home/user/bin
println(__FILE__.absolutePath) // the string /home/user/bin/foo.main.kts
println(__FILE__.parent) // the string /home/user/bin

You can also change the name of the variable using the annotation ScriptFileLocation:

@file:ScriptFileLocation("scriptPath")
println(scriptPath.absolutePath) // /home/user/bin/foo.main.kts

Keep in mind IntelliJ autocomplete doesn't love changing the variable name like that, though. :-)

So how do you run your script with kotlin-main-kts? In Kotlin 1.3.70 and above, it's as easy as ensuring your script's name ends in .main.kts. The compiler will automatically apply this special context, giving you access to __FILE__. For more information, check out the Kotlin repository here.