4

I have a multi-module sbt project and I want to run a command in the root folder of my project; hence I need to do cd ../.. .

I tried

import sys.process._
"cd ../..".! 

But I get the following:

java.io.IOException: Cannot run program "cd": error=2, No such file or directory
  at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
  at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:69)
  at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.run(ProcessBuilderImpl.scala:98)
  at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang(ProcessBuilderImpl.scala:112)
Daniel
  • 5,839
  • 9
  • 46
  • 85

1 Answers1

4

cd is not actually a program. It's a shell-internal that tells the shell to the chdir system call. Java doesn't even have a function to make the entire jvm to change its cwd (current working directory) (see Changing the current working directory in Java?) -- for Java file access, there is the user.dir property, but that's just a variable that Java functions look at.

One option is executing sh -c "...", changing the directory within the forked process, like so:

import sys.process._
val cmd = "whatever you wanted to run"
s"sh -c 'cd ../..; $cmd'".!

But better still would be to use the http://www.scala-lang.org/files/archive/api/current/index.html#scala.sys.process.Process$ factories that take both a command and a cwd:

scala.sys.process.Process("your command here", new java.io.File("/some/dir"))

To use a relative dir, you might need to create the cwd from user.dir and "../.." and/or do something like How to define a relative path in java

Community
  • 1
  • 1
Rob Starling
  • 3,868
  • 3
  • 23
  • 40