shell - 终端 cd 命令不适用于 Scala 脚本

标签 shell scala io

我需要从 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 ?

最佳答案

来自 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.



那里甚至有关于 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/

相关文章:

shell - Unix连接两个文件的多个字段

linux - 替代scp,通过开启并行连接在linux机器之间传输文件

Scala 类型参数不符合类型参数范围

scala - Scala中如何读取38位精度18位小数的数据

c - K&R C 练习 1-9 *几乎*解决

linux - 通过 ssh 命令将内容添加到 .js 文件的末尾

linux - 无法在 shell 脚本中删除文件中的行

scala - 引用与 SparkSQL CSV 不明确

c# - 如何有效地将传入数据写入磁盘?

java - 了解java.nio包中的 channel