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

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.