Reputation: 480
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`
Upvotes: 11
Views: 1424
Reputation: 1069
To get the directory of the current file in KScript, you can use the DIR
magic constant provided by Kotlin which is shown below
println(__DIR__)
For example, if your script file is located at /home/shining/script.kts, running the above code will produce the output given below
/home/shining/
This way, you can easily obtain the directory of the current script file, here are the list of examples you can see to use kotlin as an scripting language https://tutcoach.com/kotlin/kotlin-scripting/
Upvotes: 0
Reputation: 437
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.
Upvotes: 2
Reputation: 8519
You can use:
File(".")
and don't forget to import java.io.File
Upvotes: -3