我需要从 Scala 脚本运行 shell 命令,为此我使用以下代码段:
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)
代码工作正常。我想知道为什么我得到
java.io.IOException: Cannot run program "cd": error=2, No such file or directory
一旦我将命令更改为
cd /tmp && ls
IMO 相当于 ls /tmp
?
最佳答案
[...] 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.
那里甚至有关于 Java 的引用:
[...] 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 [...]
自己试试:
$ which ls
/bin/ls
$ which cd
$
简单来说,
cd
不是您可以运行的程序(进程)(如 /bin/ls
)——它更像是一个命令行指令。你想达到什么目的? Changing the current working directory in Java?或者更改您刚刚创建的进程的工作目录?
关于shell - 终端 cd 命令不适用于 Scala 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10606808/