Back to blog
September 29, 2025
3 min read

Kotlin Scripting for Automation

Run code outside projects

Kotlin Scripting for Automation

Kotlin scripting allows you to write and execute Kotlin code outside of a full project setup, making it perfect for automation tasks.

Basic Scripting

Simple Script

#!/usr/bin/env kotlin

println("Hello from Kotlin script!")

// Access command line arguments
args.forEachIndexed { index, arg ->
    println("Argument $index: $arg")
}

File Operations

#!/usr/bin/env kotlin

import java.io.File

// Read file
val content = File("input.txt").readText()
println("File content: $content")

// Write file
File("output.txt").writeText("Hello, World!")

// List directory
File(".").listFiles()?.forEach { file ->
    println("${file.name} - ${file.length()} bytes")
}

Advanced Scripting

HTTP Requests

#!/usr/bin/env kotlin

import java.net.URL
import java.net.HttpURLConnection

fun makeRequest(url: String): String {
    val connection = URL(url).openConnection() as HttpURLConnection
    connection.requestMethod = "GET"

    return connection.inputStream.bufferedReader().use { it.readText() }
}

// Usage
val response = makeRequest("https://api.example.com/data")
println(response)

JSON Processing

#!/usr/bin/env kotlin

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class User(val id: Int, val name: String)

// Parse JSON
val json = """
    {"id": 1, "name": "John Doe"}
""".trimIndent()

val user = Json.decodeFromString<User>(json)
println("User: ${user.name}")

// Create JSON
val newUser = User(2, "Jane Doe")
val newJson = Json.encodeToString(newUser)
println("JSON: $newJson")

Automation Examples

File Backup Script

#!/usr/bin/env kotlin

import java.io.File
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

fun backupDirectory(source: String, destination: String) {
    val timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"))
    val backupDir = File(destination, "backup_$timestamp")

    File(source).copyRecursively(backupDir)
    println("Backup created at: ${backupDir.absolutePath}")
}

// Usage
if (args.size >= 2) {
    backupDirectory(args[0], args[1])
} else {
    println("Usage: ./backup.kts <source> <destination>")
}

Database Migration Script

#!/usr/bin/env kotlin

import java.sql.DriverManager

fun migrateDatabase(url: String, username: String, password: String) {
    DriverManager.getConnection(url, username, password).use { connection ->
        // Create tables
        connection.createStatement().use { statement ->
            statement.execute("""
                CREATE TABLE IF NOT EXISTS users (
                    id INT PRIMARY KEY,
                    name VARCHAR(100),
                    email VARCHAR(100)
                )
            """.trimIndent())
        }

        // Insert data
        connection.prepareStatement("""
            INSERT INTO users (id, name, email)
            VALUES (?, ?, ?)
        """.trimIndent()).use { statement ->
            statement.setInt(1, 1)
            statement.setString(2, "John Doe")
            statement.setString(3, "john@example.com")
            statement.executeUpdate()
        }
    }
}

Best Practices

  1. Use shebang line
  2. Handle errors gracefully
  3. Document script usage
  4. Use appropriate libraries
  5. Consider security implications

Common Patterns

Configuration Management

#!/usr/bin/env kotlin

import java.util.Properties

fun loadConfig(path: String): Properties {
    return Properties().apply {
        load(File(path).inputStream())
    }
}

// Usage
val config = loadConfig("config.properties")
val apiKey = config.getProperty("api.key")
val endpoint = config.getProperty("api.endpoint")

Logging

#!/usr/bin/env kotlin

import java.util.logging.*

val logger = Logger.getLogger("ScriptLogger").apply {
    level = Level.INFO
    addHandler(FileHandler("script.log"))
}

fun processData(data: String) {
    logger.info("Processing data: $data")
    try {
        // Process data
        logger.info("Data processed successfully")
    } catch (e: Exception) {
        logger.severe("Error processing data: ${e.message}")
    }
}

Performance Considerations

  • Script startup time
  • Memory usage
  • Resource cleanup
  • Error handling
  • Logging overhead

Common Mistakes

  1. Not handling errors
  2. Missing shebang line
  3. Hardcoding paths
  4. Ignoring security
  5. Not cleaning up resources

Conclusion

Kotlin scripting is a powerful tool for automation tasks. Use it to create maintainable and efficient scripts for your daily tasks.