Search code examples
javalinuxgitrepo

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.

Command: 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. Can anyone help me?


Solution

  • 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.

    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:

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

    Which is obviously not what you want.

    Use a 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.