Scala: How to run an external command (process) in a different directory

This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). This is a very short recipe, Recipe 12.18, “How to run an external command (process) in a different directory.”

Problem

You want to use another directory as the base directory when running an external command in Scala.

Solution

Use one of the Process factory methods, setting your command and the desired directory, then running the process with the usual ! or !! commands. The following example runs the ls command with the -al arguments in the /var/tmp directory:

import sys.process._
import java.io.File

object Test extends App {
    val output = Process("ls -al", new File("/tmp")).!!
    println(output)
}

To run that same command in the current directory, just remove the second parameter when creating the Process:

val p = Process("ls -al")

You can use another Process factory method to set system environment variables, i.e., those that can be seen at the shell command line with set or env. See the next recipe for examples of that method.