简体   繁体   English

从Java运行Linux命令时出错

[英]Error running linux command from java

I am trying to run the below command from java code using Process process =Runtime.getRuntime().exec(command) but getting the error. 我正在尝试使用Process process =Runtime.getRuntime().exec(command)从Java代码运行以下命令,但出现错误。

Command: repo forall -c 'pwd;git status' 命令: repo forall -c 'pwd;git status'

Error: 'pwd;git: -c: line 0: unexpected EOF while looking for matching ''` I am able to run this command from linux terminal but when running from java the problem is with the space after pwd;git. 错误: 'pwd;git: -c: line 0: unexpected EOF while looking for matching我能够从linux终端运行此命令,但是从Java运行时,问题出在pwd; git之后。 Can anyone help me? 谁能帮我?

This is an ultra classical mistake and I am frankly surprised that you didn't find the answer to it by searching around. 这是一个非常经典的错误,坦率地说,您没有四处搜寻找不到答案,这让我感到惊讶。

A Process is not a command interpreter. Process不是命令解释器。

However, Runtime.exec() will still try and act as one if you pass it only one argument, and here you'll end up splitting like this: 但是,如果仅向其传递一个参数,则Runtime.exec()仍将尝试作为一个参数,在这里,您最终将像这样分裂:

  • repo
  • forall
  • -c
  • 'pwd;git
  • status'

Which is obviously not what you want. 显然这不是您想要的。

Use a ProcessBuilder . 使用ProcessBuilder I won't do it all for you but here is how to start: 我不会为您做所有这一切,但是这是开始的方法:

final Process p = new ProcessBuilder()
    .command("repo", "forall", "-c", "pwd; git status")
    // etc etc
    .start();

Link to the javadoc . 链接到javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM