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:

JavaScript

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:

JavaScript

Thanks in advance!

Advertisement

Answer

Here’s the shell command you want to execute:

JavaScript

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):

JavaScript

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

JavaScript

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:

JavaScript

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

JavaScript

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):

JavaScript
Advertisement