Modifying environment variable for a process with scala.sys.process?
Asked Answered
P

1

14

I want to run my process from scala, with several environment variables modified. For example:

Seq("bash","echo $asdf") !

and $asdf set to some value. Is there a way to do this from scala?

EDIT:

The closest I got to it so far:

val pb = new java.lang.ProcessBuilder("bash","echo $asdf")
pb.environment.put("asdf","value") }
val p = pb.start()
io.Source.fromInputStream(p.getInputStream).getLines.toList.foreach(println)
p.waitFor()

But this is ugly.

Pyroclastic answered 25/2, 2012 at 10:27 Comment(2)
BTW, You can do it just like you do in Java: import java.util._ Runtime.getRuntime().exec("echo $PATH")Redheaded
@Redheaded You can omit parens. In fact, see sys.runtime.Hatching
P
19
Process(Seq("bash", "-c", "echo $asdf"), None, "asdf" -> "Hello, world!").!

See Process.

Pitsaw answered 25/2, 2012 at 13:26 Comment(4)
For the first time ever, my answer is longer than the Sobral answer it duplicates. Ironically, this answer more precisely answers what the duplicate question was probably trying to ask. https://mcmap.net/q/830069/-how-to-set-environmental-variable-from-scalaHatching
@Hatching This was a rather poor answer of mine. Shame on me! :)Pitsaw
I tried this and it doesn't work, it tries to interpret "echo $asdf" as an executable -- gives bash: echo $asdf: No such file or directory.Concepcion
I got it working adding a -c: Process(Seq("bash", "-c", "echo $asdf"), None, "asdf" -> "Hello, world!").!Concepcion

© 2022 - 2024 — McMap. All rights reserved.