I need to run a shell command from a Scala script and I use the following snippet for that:
import scala.sys.process.{Process, ProcessIO}
val command = "ls /tmp"
val process = Process(command)
val processIO = new ProcessIO(_ => (),
stdout => scala.io.Source.fromInputStream(stdout).getLines.foreach(println),
_ => ())
process.run(processIO)
The code works fine. I'm wondering why I get
java.io.IOException: Cannot run program "cd": error=2, No such file or directory
as soon as I change the command to cd /tmp && ls
which is IMO equivalent to ls /tmp
?
From Wikipedia on cd
command:
[...] on Unix systems
cd
calls thechdir()
POSIX C function. This means that when the command is executed, no new process is created to migrate to the other directory as is the case with other commands such asls
. Instead, the shell itself executes this command.
There is even a quote about Java there:
[...] neither the Java programming language nor the Java Virtual Machine supports
chdir()
directly; a change request remained open for over a decade while the team responsible for Java considered the alternatives, though by 2008 the request was denied after only limited support was introduced [...]
Try it yourself:
$ which ls
/bin/ls
$ which cd
$
In simple words, cd
is not a program (process) you can run (like /bin/ls
) - it is more of a command line directive.
What do you want to achieve? Changing the current working directory in Java? or change the working directory of the process you just created?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With