Created
February 1, 2021 15:44
-
-
Save Pooh3Mobi/b49b43ed23d055d8c8584b95f09b6615 to your computer and use it in GitHub Desktop.
"ls -al".runCommand()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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