Run a compound shell command from Java/Groovy

2019-09-13 09:17发布

I got stuck trying to run a compound shell command from a Groovy script. 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. 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. I tried wrapping the command in single quotes and giving it to '/bin/sh -c' but nothing works.

How do you run a compound shell command from Java? I know I've done this in the past but I cannot figure it out today.

2条回答
迷人小祖宗
2楼-- · 2019-09-13 09:58

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.

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

EDIT:

Have you tried using a ProcessBuilder? This seems to work on my OSX box:

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();
}
查看更多
男人必须洒脱
3楼-- · 2019-09-13 10:10

With groovy, the list form of execute should work:

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

查看更多
登录 后发表回答