12.18. Setting Environment Variables When Running Commands

Problem

You need to set one or more environment variables when running an external command.

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

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.