Skip to content
Advertisement

Executing mv command with Java.exec();

I am trying to move an file via the linux mv command. I have following code:

processBuilder.command("/bin/sh", "-c", ""mv", """ + rawOutput + "/" + dir + "/build/libs/*"", """ + startDir + "/test.jar""");

During execution it translates to

/bin/sh -c “mv “/home/test/update/Test-test-23afi369890Ajk/build/libs/*” “/home/test/test.jar””

While this command executes perfectly via the command line, it fails during execution of the jar. Following error is given:

"/home/test/update/Test-test-23afi369890Ajk/build/libs/*": 1: "/home/test/update/Test-test-23afi369890Ajk/build/libs/*": Syntax error: Unterminated quoted string

Thanks in advance!

Advertisement

Answer

Here’s the shell command you want to execute:

mv /home/test/update/Test-test-23afi369890Ajk/build/libs/* /home/test/test.jar

Here’s the Java concatenation that builds this shell command in Java (you should print and copy-paste it to a shell to verify it):

String myCmd = "mv " + rawOutput + "/build/libs/* " + dir + "/test.jar";

Here’s how you can run it in a shell:

processBuilder.command("/bin/sh", "-c", myCmd);

This gives the following argument list:

  1. /bin/sh
  2. -c
  3. mv /home/test/update/Test-test-23afi369890Ajk/build/libs/* /home/test/test.jar

And for completeness, here’s how you should have designed it, with a static command string and passing in the arguments as separate parameters to avoid shell injection:

String myCmd = "mv "$1"/build/libs/* "$2"/test.jar";
processBuilder.command("/bin/sh", "-c", myCmd, "_", rawOutput, dir);

Whose argument list is:

  1. /bin/sh
  2. -c
  3. mv "$1"/build/libs/* "$2"/test.jar
  4. _
  5. /home/test/update/Test-test-23afi369890Ajk
  6. /home/test

(the _ becomes $0, i.e. the script’s filename for use in error messages and similar)

During execution [my attempt] translates to

/bin/sh -c "mv "/home/test/update/Test-test-23afi369890Ajk/build/libs/*" "/home/test/test.jar""

I don’t know how you reached this conclusion. The actual argument list it expands to is:

  1. /bin/sh
  2. -c
  3. "mv
  4. "/home/test/update/Test-test-23afi369890Ajk/build/libs/*"
  5. "/home/test/test.jar""

This corresponds to the following shell command which probably fails with the same error messages as your Java program (if you’re not suppressing stderr):

$ /bin/sh -c '"mv' '"/home/test/update/Test-test-23afi369890Ajk/build/libs/*"' '"/home/test/test.jar""'
"/home/test/update/Test-test-23afi369890Ajk/build/libs/*": 1: Syntax error: Unterminated quoted string
Advertisement