jakubriegel / kotlin-shell

Tool for performing shell-like programing in Kotlin
Apache License 2.0
143 stars 8 forks source link

Running piped commands seems not to work #9

Open aartiPl opened 3 years ago

aartiPl commented 3 years ago

I am trying to run the following command in kotlin-shell:

`

!/usr/bin/env kscript

import eu.jrie.jetbrains.kotlinshell.shell.*

shell { println("wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | apt-key add -"()) }

`

But it looks like it doesn't work correctly and prints as an output result of the first command, instead of the output of both of them.

On the other hand, I was able to implement similar functionality in few lines of code, and this approach works:

`

import java.io.File import java.util.concurrent.TimeUnit

data class ProcessResult(val exitCode: Int, val systemOut: String, val systemErr: String)

fun String.shellRun(workingDir: File? = null, waitTimeSec: Long = 60, throwException: Boolean = true): ProcessResult { val proc = ProcessBuilder("/bin/sh", "-c", this).directory(workingDir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start()

val exitedNormally = proc.waitFor(waitTimeSec, TimeUnit.SECONDS)

if (!exitedNormally) {
    throw IllegalStateException("Command has timed out after $waitTimeSec seconds.")
}

val processResult = ProcessResult(proc.exitValue(),
                                  proc.inputStream.bufferedReader().readText().trim(),
                                  proc.errorStream.bufferedReader().readText().trim())

if (throwException && processResult.exitCode != 0) {
    throw IllegalStateException("Command failed.\n$this\n${processResult.systemErr}")
}

return processResult

}

println("wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | apt-key add -".shellRun()) println("echo deb https://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list".shellRun()) println("apt update;apt -y install jenkins".shellRun())

`

Is it possible to add the above functionality to kotlin-shell? It would be a great help with moving real bash configuration scripts into Kotlin.