Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminal cd command not working from Scala script

Tags:

shell

io

scala

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?

like image 406
nab Avatar asked May 15 '12 18:05

nab


1 Answers

From Wikipedia on cd command:

[...] on Unix systems cd calls the chdir() 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 as ls. 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?

like image 107
Tomasz Nurkiewicz Avatar answered Nov 06 '22 10:11

Tomasz Nurkiewicz