Coming Up for Air

Executable Kotlin Scripts

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:

println("Hello, world!")

You can then run it like this:

$ 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:

#!/usr/bin/env -S kotlinc -script
println("Hello, world!")

Then we set the executable bit and run it:

$ chmod +x test.kts
$ ./test.kts
Hello, world!

Easy peasy. Now you a more powerful language in your shell scripting toolbox. Enjoy!

tags: Kotlin


Sample quote

Quote source