10

Sorry but I could not find the answer from googling...what is the syntax for running a bash command in kotlin? I would like to do a curl command. The documentation out there seems very limited or maybe I am bad at googling?

Michael
  • 283
  • 1
  • 3
  • 15
  • I don't see a link to the excellent [How to invoke external command from within Kotlin code?](https://stackoverflow.com/questions/35421699/how-to-invoke-external-command-from-within-kotlin-code) – allenjom Nov 04 '19 at 17:12

2 Answers2

19

As curl is not a bash-specific application, you can just start it like any other process. Assuming you are using kotlin on the JVM:

val process = ProcessBuilder("curl", "https://example.com").start()
process.inputStream.reader(Charsets.UTF_8).use {
  println(it.readText())
}
process.waitFor(10, TimeUnit.SECONDS)

Instead of using curl you might want to look into kotlin or java libraries, depending on your problem it could be easier and even faster than starting the curl process.

Boris
  • 4,327
  • 2
  • 19
  • 27
  • Can I still use external libraries like unirest even if it is a kotlin script ? – Michael Oct 07 '17 at 18:16
  • If you are running the script with kotlinc you can just specify the classpath: `kotlinc -script test.kts -classpath library.jar` – Boris Oct 10 '17 at 15:25
11

You can do that simply with Runtime.getRuntime().exec("command line").

Since Kotlin is based on Java, you can find documentation in JavaDoc here: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String)

Václav Hodek
  • 638
  • 4
  • 9