Scala: How to set environment variables when running external commands

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 12.19, “How to set environment variables when running external commands in Scala.”

Problem

You need to set one or more environment variables when running an external command in a Scala application.

Solution

Specify the environment variables when calling a Process factory method (an apply method in the Process object).

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 Process constructor:

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.”

See Also