Executable Kotlin Scripts
Monday, December 23, 2019 |A user in #kotlin on Freenode asked how to run a Kotlin script. While the Kotlin docs are pretty clear on how to do that, I thought I’d make a quick post to show how to make an easily executable Kotlin script.
The first step is to name the file with a .kts
extension:
1
println("Hello, world!")
You can then run it like this:
1
2
$ kotlinc -script test.kts
Hello, world!
That’s pretty cool (and pretty quick on my laptop), but the command line is a bit cumbersome. Let’s fix that with two small changes. First, let’s add a shebang:
1
2
#!/usr/bin/env -S kotlinc -script
println("Hello, world!")
Then we set the executable bit and run it:
1
2
3
$ chmod +x test.kts
$ ./test.kts
Hello, world!
Easy peasy. Now you a more powerful language in your shell scripting toolbox. Enjoy!