简体   繁体   English

从Java / Groovy运行复合Shell命令

[英]Run a compound shell command from Java/Groovy

I got stuck trying to run a compound shell command from a Groovy script. 我在尝试从Groovy脚本运行复合shell命令时遇到了麻烦。 It was one of those commands where you separate with "&&" so that the 2nd command never runs if the 1st one fails. 这是用“ &&”分隔的命令之一,因此如果第一个命令失败,则第二个命令将永远不会运行。 For whatever reason I couldn't get it to work. 无论出于什么原因,我都无法正常工作。 I was using: 我正在使用:

println "custom-cmd -a https://someurl/path && other-cmd -f parameter".execute([], new File('/some/dir')).text

The shell kept misinterpreting the command throwing errors like "custom-cmd -f invalid option" It was like it was ignoring the "&&" in between. Shell不断误解命令抛出的错误,例如“ custom-cmd -f无效选项”。这就像忽略了两者之间的“ &&”一样。 I tried using a semi-colon as well but was not lucky. 我也尝试使用分号,但并不幸运。 I tried using straight Java APIs Runtime.getRuntime().exec() and splitting the command into an array. 我尝试使用直接Java API Runtime.getRuntime()。exec()并将命令拆分为一个数组。 I tried wrapping the command in single quotes and giving it to '/bin/sh -c' but nothing works. 我尝试将命令包装在单引号中,并将其提供给'/ bin / sh -c',但没有任何效果。

How do you run a compound shell command from Java? 如何从Java运行复合Shell命令? I know I've done this in the past but I cannot figure it out today. 我知道我过去曾经做过,但是今天我无法弄清楚。

With groovy, the list form of execute should work: 使用groovy,execute的列表形式应该可以工作:

def out = ['bash', '-c', "custom-cmd -a https://someurl/path && other-cmd -f parameter"].execute([], new File('/some/dir')).text

Of course you may want to use the consumeProcessOutput method on process, as if the output is too large, calling text may block 当然,您可能要在进程上使用consumeProcessOutput方法,就像输出太大一样,调用文本可能会阻塞

Try something like: 尝试类似:

Runtime.getRuntime().exec("cmd /c \\"start somefile.bat && start other.bat && cd C:\\\\test && test.exe\\"");

Runtime.getRuntime().exec() can be used without splitting the commands into an array. 可以使用Runtime.getRuntime().exec()而不将命令拆分为一个数组。

see https://stackoverflow.com/a/18867097/1410671 参见https://stackoverflow.com/a/18867097/1410671

EDIT: 编辑:

Have you tried using a ProcessBuilder ? 您是否尝试过使用ProcessBuilder This seems to work on my OSX box: 这似乎可以在我的OSX机器上使用:

public static void main(String[] args) throws IOException {
    ProcessBuilder builder = new ProcessBuilder( "/bin/sh", "-c", "echo '123' && ls" );

    Process p=null;
    try {
        p = builder.start();
    }
    catch (IOException e) {
        System.out.println(e);
    }


    Scanner s = new Scanner( p.getInputStream() );
    while (s.hasNext())
    {
        System.out.println( s.next() );
    }
    s.close();
}

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

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