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

This is an excerpt from 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.”


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


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

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

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.

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.