Skip to content

Instantly share code, notes, and snippets.

@Pooh3Mobi
Created February 1, 2021 15:44
Show Gist options
  • Save Pooh3Mobi/b49b43ed23d055d8c8584b95f09b6615 to your computer and use it in GitHub Desktop.
Save Pooh3Mobi/b49b43ed23d055d8c8584b95f09b6615 to your computer and use it in GitHub Desktop.
"ls -al".runCommand()
// https://stackoverflow.com/a/52441962
fun String.runCommand(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
onErrorReturn: (Throwable) -> String = { "error: ${it.message}" }
): String {
val result = runCatching {
val parts = this.split("\\s".toRegex())
val proc = ProcessBuilder(*parts.toTypedArray())
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
proc.waitFor(timeoutAmount, timeoutUnit)
proc.inputStream.bufferedReader().readText()
}
return result.recover(onErrorReturn).getOrNull() ?: error("cannot get result.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment