12.17. How to Run a Process in a Different Directory
Problem
You want to use another directory as the base directory when running an external command.
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.
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.