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.