Kotlin scripts easier than kscript

Paweł Szymański
1 min readSep 21, 2020

Unix bash scripts, Windows batch scripts — hard to manage for a Kotlin programmer.

Kscript has it’s issues: it’s not the same as Kotlin, hard to debug, different method of adding imports than standard Kotlin etc.

Happily you can make a simple command line Kotlin app.
Full example available here:

https://github.com/stasheq/kotlin_cmd_exec

gradle.kts

plugins {
id("kotlin")
id("application")
}
application {
mainClassName = "me.szymanski.kotlinexec.example.Main"
}
dependencies {
implementation("me.szymanski.kotlinexec:kotlin-exec-lib:1.0")
}

Main.kt

import me.szymanski.kotlinexec.exec
import java.lang.Exception
import kotlin.system.exitProcess
object Main {
@JvmStatic
fun main(args: Array<String>) {
try {
println("Received arguments: ${args.joinToString(", ")}")
"echo \"Hello world\"".exec()
} catch (e: Exception) {
e.printStackTrace()
println(e.message)
exitProcess(SCRIPT_FAILED_CODE)
}
}

private const val SCRIPT_FAILED_CODE = -1
}

dependency kotlin-exec-lib

It provides String.exec() function.

"echo Hello World".exec()
"mkdir newDir".exec()
"git status".exec()
...

plugin id(“application”)

https://docs.gradle.org/current/userguide/application_plugin.html

It makes it possible to compile project as an app, then run it with command line arguments.

To build:

./gradlew example:installDist

installDist installs app in ./build/install/projectName

Run

./example/build/install/example/bin/example 1st-param 2nd-param

Output

Received arguments: 1st-param, 2nd-param
echo "Hello world"
Hello world

--

--