Running OS commands

suggest change

Sometimes the easiest way to get something done is to run another program: git to get the current commit, ffmpeg to convert a video, docker to start a container, or a shell script someone already wrote.

Kotlin on the JVM runs external programs with java.lang.ProcessBuilder. There is no separate Kotlin standard library API for it, but Kotlin's extension functions, use { } and coroutines make the Java API pleasant to work with.

The examples were run on Linux with JDK 25. Everything also works on macOS and Windows, but the commands themselves (ls, sort, sh) are Unix programs. See the Windows section below.

Run a command and read its output

fun main() {
    val process = ProcessBuilder("git", "--version").start()
    val output = process.inputReader().readText() // read all of stdout
    val exitCode = process.waitFor()              // wait for the process to end
    println("exit code: $exitCode")
    println("output: ${output.trim()}")
}
exit code: 0
output: git version 2.53.0

The parts:

The program is looked up in the directories listed in the PATH environment variable. You can also give an absolute path like /usr/bin/git.

If the program can't be found or isn't executable, start() throws an IOException:

import java.io.IOException

fun main() {
    try {
        ProcessBuilder("no-such-program", "--help").start()
    } catch (e: IOException) {
        println(e.message)
    }
}
Cannot run program "no-such-program": Exec failed, error: 2 (No such file or directory)

A program that runs and fails is different: it doesn't throw anything, it just returns a non-zero exit code. Your code has to check it.

Throwing on a non-zero exit code

Most of the time you want a failed command to be an error. A small helper takes care of it:

class CommandException(val command: List<String>, val exitCode: Int, val output: String) :
    Exception("command $command failed with exit code $exitCode: ${output.trim()}")

fun exec(vararg command: String): String {
    val process = ProcessBuilder(*command)
        .redirectErrorStream(true) // merge stderr into stdout
        .start()
    val output = process.inputReader().readText()
    val exitCode = process.waitFor()
    if (exitCode != 0) throw CommandException(command.toList(), exitCode, output)
    return output
}

fun main() {
    println(exec("git", "--version").trim())
    try {
        exec("git", "no-such-subcommand")
    } catch (e: CommandException) {
        println(e.message)
    }
}
git version 2.53.0
command [git, no-such-subcommand] failed with exit code 1: git: 'no-such-subcommand' is not a git command. See 'git --help'.

redirectErrorStream(true) sends the child's stderr to the same pipe as stdout, so there's one stream to read and the error message ends up in the exception. The * spread operator passes the vararg array on to ProcessBuilder (see Vararg Parameters in Functions). For your own exception classes, keeping the exit code and output as properties lets callers handle specific failures.

Capturing stdout and stderr separately

When you need stdout and stderr as two separate strings, there's a trap. Each pipe between the processes has a small OS buffer, usually 64 KB on Linux. If the child writes a lot to stderr while you're blocked reading stdout until it ends, the stderr buffer fills, the child blocks writing to it and never finishes, and both programs wait for each other forever.

The fix is to read both streams at the same time, one of them on another thread:

import java.io.File

data class CommandResult(val exitCode: Int, val stdout: String, val stderr: String)

fun runCommand(vararg command: String, dir: File? = null): CommandResult {
    val process = ProcessBuilder(*command)
        .directory(dir)
        .start()
    // read stderr on a background thread so neither pipe can fill up and block
    var stderr = ""
    val errReader = Thread { stderr = process.errorReader().readText() }.apply { start() }
    val stdout = process.inputReader().readText()
    errReader.join()
    return CommandResult(process.waitFor(), stdout, stderr)
}

fun main() {
    val ok = runCommand("ls", "src")
    println(ok)

    val bad = runCommand("ls", "no-such-dir")
    println("exit=${bad.exitCode} stderr=${bad.stderr.trim()}")
}
CommandResult(exitCode=0, stdout=a.kt
b.kt
notes.txt
, stderr=)
exit=2 stderr=ls: cannot access 'no-such-dir': No such file or directory

join() makes the value written by the background thread visible to the caller. The coroutine version below does the same thing without managing threads by hand.

The same deadlock happens if you call waitFor() before reading the output. Read first, then wait. If you don't need the output, don't leave the pipe unread: redirect it to a file or discard it (next sections).

Working directory and environment

By default the child runs in the current directory of your program and inherits all its environment variables. Both can be changed before start():

import java.io.File

fun main() {
    val pb = ProcessBuilder("sh", "-c", "echo \"dir=\$(pwd) greeting=\$GREETING home=\${HOME:-unset}\"")
    pb.directory(File("/tmp"))
    val env = pb.environment() // a mutable copy of this process's environment
    env["GREETING"] = "hello"
    env.remove("HOME")
    pb.redirectErrorStream(true)

    val p = pb.start()
    print(p.inputReader().readText())
    p.waitFor()
}
dir=/tmp greeting=hello home=unset

environment() returns a MutableMap<String, String>. Changes only affect processes started from this builder, never your own process. Call env.clear() first to start the child with an empty environment.

Kotlin needs \$ in the string to send a literal $ to the shell instead of starting a string template. A raw string avoids the escaping for longer scripts.

A ProcessBuilder is reusable: you can call start() on it several times, and change it between calls.

Redirecting input and output

Instead of piping data through your program, you can connect the child's streams directly to files, to your own terminal, or to nothing:

import java.io.File

fun main() {
    // the child writes straight to our terminal
    val code = ProcessBuilder("ls", "src")
        .inheritIO()
        .start()
        .waitFor()
    println("ls finished with $code")

    // stdout to a file, stderr appended to another file
    val out = File("listing.txt")
    val log = File("errors.log")
    ProcessBuilder("ls", "src", "missing-dir")
        .redirectOutput(out)
        .redirectError(ProcessBuilder.Redirect.appendTo(log))
        .start()
        .waitFor()
    println("listing.txt: " + out.readLines())
    println("errors.log: " + log.readText().trim())

    // stdin from a file
    val wc = ProcessBuilder("wc", "-l")
        .redirectInput(File("fruits.txt"))
        .start()
    println("lines: " + wc.inputReader().readText().trim())
    wc.waitFor()

    // throw away output we don't care about
    ProcessBuilder("ls", "-R", "/usr/share")
        .redirectOutput(ProcessBuilder.Redirect.DISCARD)
        .redirectError(ProcessBuilder.Redirect.DISCARD)
        .start()
        .waitFor()
}
a.kt
b.kt
notes.txt
ls finished with 0
listing.txt: [src:, a.kt, b.kt, notes.txt]
errors.log: ls: cannot access 'missing-dir': No such file or directory
lines: 4

The options for each stream:

Redirect Meaning
Redirect.PIPE the default: read or write it from your program
Redirect.INHERIT share your program's stdin/stdout/stderr, e.g. the terminal
Redirect.DISCARD throw output away (like > /dev/null)
Redirect.to(file) / redirectOutput(file) overwrite a file (like >)
Redirect.appendTo(file) append to a file (like >>)
Redirect.from(file) / redirectInput(file) read stdin from a file (like <)

inheritIO() sets all three to INHERIT. It's what you want for a build tool or a script that runs git commit or vim: the user sees the output live and can type into the child. When a stream is redirected, the matching Process stream (inputReader() and so on) is an empty stream that you don't need to read.

Writing to stdin

To feed data to a program, write to outputWriter() and close it when you're done. Many programs, like sort, read until end-of-file and don't produce anything until stdin is closed:

fun main() {
    val process = ProcessBuilder("sort").start()

    // write the input, then close stdin so sort sees end-of-file
    process.outputWriter().use { w ->
        listOf("pear", "fig", "apple").forEach { w.write(it); w.newLine() }
    }

    print(process.inputReader().readText())
    println("exit: ${process.waitFor()}")
}
apple
fig
pear
exit: 0

use { } closes the writer even if an exception is thrown. Writing a large input this way has the same buffer problem as before: if the child produces output while you're still writing, write on one thread and read on another.

Streaming output line by line

readText() waits for the process to end. For long-running commands, process the output as it arrives:

fun main() {
    val script = "for i in 1 2 3; do echo \"step \$i\"; sleep 1; done; echo oops >&2"
    val process = ProcessBuilder("sh", "-c", script)
        .redirectErrorStream(true)
        .start()

    val start = System.nanoTime()
    process.inputReader().useLines { lines ->
        lines.forEach { line ->
            val t = (System.nanoTime() - start) / 1_000_000_000.0
            println("[%.1fs] %s".format(t, line))
        }
    }
    println("exit: ${process.waitFor()}")
}
[0.0s] step 1
[1.0s] step 2
[2.0s] step 3
[3.0s] oops
exit: 0

useLines gives you a lazy sequence of lines and closes the reader afterwards. Each line is handled as soon as the child prints it.

Some programs buffer their output when it goes to a pipe instead of a terminal and only flush it every few kilobytes or at exit. If lines arrive in big bursts, that's the child's buffering, not Kotlin's. Look for a flag like --line-buffered (grep), -u (python), or run it with stdbuf -oL on Linux.

The input is decoded with the platform's default charset, which is UTF-8 on Java 18 and newer. If a program writes something else, pass the charset: process.inputReader(Charsets.ISO_8859_1). See Unicode and encodings.

Timeouts and killing a process

waitFor(timeout, unit) waits at most that long and returns true if the process exited:

import java.util.concurrent.TimeUnit

fun main() {
    val process = ProcessBuilder("sleep", "30").start()

    if (!process.waitFor(2, TimeUnit.SECONDS)) {
        println("still running after 2s, stopping pid ${process.pid()}")
        process.destroy()                         // SIGTERM
        if (!process.waitFor(5, TimeUnit.SECONDS)) {
            process.destroyForcibly()             // SIGKILL
            process.waitFor()
        }
    }
    println("alive: ${process.isAlive}, exit code: ${process.exitValue()}")
}
still running after 2s, stopping pid 1890
alive: false, exit code: 143

The timeout only limits waiting. If you are reading the output with readText() on the same thread, that call blocks until the process exits, so the timeout is never reached. Read on another thread (or a coroutine, below), or redirect the output to a file.

Killing child processes too

destroy() stops only the process you started. If that process started its own children, like a shell script or npm run, they keep running. descendants() lists them:

import java.util.concurrent.TimeUnit

fun main() {
    // sh starts two sleep processes; killing sh alone would leave them running
    val process = ProcessBuilder("sh", "-c", "sleep 100 & sleep 100 & wait").start()
    Thread.sleep(500)

    val children = process.descendants().toList()
    println("descendants: ${children.map { "pid " + it.pid() }}")

    children.forEach { it.destroy() }
    process.destroy()
    process.waitFor(5, TimeUnit.SECONDS)
    Thread.sleep(200)
    println("sh alive: ${process.isAlive}, children alive: ${children.count { it.isAlive }}")
}
descendants: [pid 633, pid 634]
sh alive: false, children alive: 0

Child processes are not killed when your JVM exits, either. A program that starts long-running processes should stop them in a shutdown hook.

Shells, globs and pipes

ProcessBuilder starts the program directly. Features that you know from the command line, like * globs, | pipes, > redirections, &&, ~ and $VAR, are provided by the shell, so they don't work unless you run a shell:

fun output(vararg command: String): String {
    val p = ProcessBuilder(*command).redirectErrorStream(true).start()
    return p.inputReader().readText().trim().also { p.waitFor() }
}

fun main() {
    // no shell: '*' and '|' are passed to ls literally
    println(output("ls", "src/*.kt"))

    // with a shell: globs, pipes and redirections work
    println(output("sh", "-c", "ls src/*.kt | wc -l"))

    // passing untrusted values: as separate arguments, never inside the script
    val name = "x; echo INJECTED"
    println(output("sh", "-c", "echo \"hello \$1\"", "sh", name))
    println(output("sh", "-c", "echo hello $name")) // vulnerable
}
ls: cannot access 'src/*.kt': No such file or directory
2
hello x; echo INJECTED
hello x
INJECTED

The last line shows command injection. Putting a value into the shell script with a Kotlin string template lets that value run any command it likes. If the value comes from a user, a file name or a web request, that's a serious security hole. The safe ways:

Often you don't need a shell at all. Kotlin can list files (see Files and I/O), and pipes can be built with startPipeline.

Pipelines without a shell

ProcessBuilder.startPipeline connects the stdout of each process to the stdin of the next one, like | in a shell:

fun main() {
    // equivalent of: cat fruits.txt | sort | uniq -c | sort -rn
    val processes = ProcessBuilder.startPipeline(
        listOf(
            ProcessBuilder("cat", "fruits.txt"),
            ProcessBuilder("sort"),
            ProcessBuilder("uniq", "-c"),
            ProcessBuilder("sort", "-rn"),
        )
    )
    val last = processes.last()
    print(last.inputReader().readText())
    processes.forEach { it.waitFor() }
    println("exit codes: ${processes.map { it.exitValue() }}")
}
      2 apple
      1 cherry
      1 banana
exit codes: [0, 0, 0, 0]

You read from the last process and get the exit code of every stage. A shell only reports the last one, unless you use set -o pipefail. The data flows directly between the processes through OS pipes and never passes through the JVM.

Running commands with coroutines

waitFor() and readText() block a thread. With coroutines you can run many commands at once, wait for exit without blocking, and cancel them. Process.onExit() returns a CompletableFuture, and await() from kotlinx-coroutines-core waits for it by suspending:

import kotlinx.coroutines.*
import kotlinx.coroutines.future.await

suspend fun runAsync(vararg command: String): Pair<Int, String> = coroutineScope {
    val process = ProcessBuilder(*command).redirectErrorStream(true).start()
    try {
        val output = async(Dispatchers.IO) { process.inputReader().readText() }
        val exitCode = process.onExit().await().exitValue() // suspends, doesn't block a thread
        exitCode to output.await().trim()
    } finally {
        process.destroy() // on cancellation: kill the process; no-op if it already exited
    }
}

fun main() = runBlocking {
    var start = System.currentTimeMillis()
    val results = listOf(
        async { runAsync("sh", "-c", "sleep 1; echo first") },
        async { runAsync("sh", "-c", "sleep 1; echo second") },
        async { runAsync("sh", "-c", "sleep 1; echo third >&2; exit 3") },
    ).awaitAll()
    results.forEach(::println)
    println("took ${(System.currentTimeMillis() - start) / 100 * 100} ms")

    start = System.currentTimeMillis()
    val r = withTimeoutOrNull(500) { runAsync("sleep", "10") }
    println("result: $r after ${(System.currentTimeMillis() - start) / 100 * 100} ms")
}
(0, first)
(0, second)
(3, third)
took 1200 ms
result: null after 500 ms

Three one-second commands ran in parallel and finished in a little over a second.

The finally block matters. Reading a pipe can't be interrupted, so a coroutine stuck in readText() ignores cancellation. When withTimeoutOrNull cancels runAsync, await() throws CancellationException, finally kills the process, the pipe closes, and the reading coroutine finishes right away. Without destroy(), the timeout would still wait the full 10 seconds for sleep to exit. See Cancellation and timeouts.

The dependency in Gradle:

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
}

Process information with ProcessHandle

ProcessHandle gives you information about your own process, processes you started, and any other process on the machine:

fun main() {
    val me = ProcessHandle.current()
    println("my pid: ${me.pid()}")
    println("parent pid: ${me.parent().map { it.pid() }.orElse(-1)}")

    val p = ProcessBuilder("sleep", "5").start()
    val info = p.toHandle().info()
    println("child pid=${p.pid()} command=${info.command().orElse("?").substringAfterLast('/')} args=${info.arguments().map { it.toList() }.orElse(emptyList())}")
    p.onExit().thenAccept { println("child ${it.pid()} exited with ${it.exitValue()}") }
    p.destroy()
    p.onExit().join()

    val javaCount = ProcessHandle.allProcesses()
        .filter { it.info().command().orElse("").endsWith("/java") }
        .count()
    println("java processes running: $javaCount")
}
my pid: 489
parent pid: 487
child pid=633 command=sleep args=[5]
child 633 exited with 143
java processes running: 1

info() also has startInstant(), totalCpuDuration() and user(). All its values are Optional, because the OS may not let you see them, for example for processes owned by other users. ProcessHandle.of(pid) finds a process by its PID, and its destroy() can stop processes you didn't start, if you have permission.

Windows

The API is the same on Windows, but a few things are different:

A portable helper picks the shell based on the OS:

fun output(vararg command: String): String {
    val p = ProcessBuilder(*command).redirectErrorStream(true).start()
    return p.inputReader().readText().trim().also { p.waitFor() }
}

fun main() {
    val isWindows = System.getProperty("os.name").startsWith("Windows")
    println(System.getProperty("os.name"))
    // 'echo' is built into cmd.exe, not a program
    val cmd = if (isWindows) listOf("cmd.exe", "/c", "echo %OS%") else listOf("sh", "-c", "uname")
    println(output(*cmd.toTypedArray()))
}

Output on Windows:

Windows 11
Windows_NT

Runtime.exec

Older code often uses Runtime.getRuntime().exec(...). It's a thin wrapper around ProcessBuilder. The version that takes a single string was deprecated in Java 18, because it splits the string on whitespace and ignores quotes, which surprises everyone:

fun main() {
    // deprecated: the string is split on whitespace, quotes mean nothing
    val p1 = Runtime.getRuntime().exec("echo 'a    b'")
    println(p1.inputReader().readText().trim())
    // fine: each argument is a separate array element
    val p2 = Runtime.getRuntime().exec(arrayOf("echo", "a    b"))
    println(p2.inputReader().readText().trim())
}
'a b'
a    b

The Kotlin compiler warns: 'fun exec(p0: String!): Process!' is deprecated. Deprecated in Java. Use ProcessBuilder in new code. It has all the features (redirects, working directory, environment) in one place.

Gotchas

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents