You need to set one or more environment variables when running an external command in a Scala application.
Specify the environment variables when calling a
Process factory method (an
apply method in the
The following example shows how to run a shell script in a directory named /home/al/bin while also setting the
PATH environment variable:
val p = Process("runFoo.sh", new File("/Users/Al/bin"), "PATH" -> ".:/usr/bin:/opt/scala/bin") val output = p.!!
To set multiple environment variables at one time, keep adding them at the end of the
val output = Process("env", None, "VAR1" -> "foo", "VAR2" -> "bar")
These examples work because of the overloaded
apply methods in the
Process object. For instance, one method takes a
File for the
directory parameter, and another method takes an
Option[File] for that parameter. This second approach lets you use
None to indicate the current directory.
The ability to specify multiple environment variables when calling a
Process factory method works because the
apply methods accept a varargs argument of the type
(String, String)* for their last argument. This means “a variable number of tuple arguments.”
The Scala Cookbook
This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly.