7

Possible Duplicate:
run shell command from java

I want to export some variable so I have this command.

Runtime.getRuntime().exec("export a=b");

what is wrong with this command because this throw exeption:

java.io.IOException: Cannot run program "export": java.io.IOException: error=2, No such file or directory

Community
  • 1
  • 1
hudi
  • 15,555
  • 47
  • 142
  • 246
  • 1
    You can use ProcessBuilder. See this question - http://stackoverflow.com/questions/525212/how-to-run-unix-shell-script-from-java-code – Manish Aug 01 '12 at 11:32
  • 2
    Depends on what you want to accomplish. You can run a shell command by invoking `bash` in a `ProcessBuilder`, but the effect of the `export` will extend only to that invocation. You cannot modify the parent shell's environment from within a Java program. – Jim Garrison Aug 01 '12 at 19:38
  • @JimGarrison's comment should be the accepted solution. It depends on what the user is aiming to accomplish. I found this answer very useful which contains an example similar to @Manish's link, but with examples for both `ProcessBuilder` as well as `Runtime.exec()` http://stackoverflow.com/a/7370477/3196753 – tresf Mar 23 '16 at 18:31

1 Answers1

3

export is a shell command, not a program.The best way to do this would be to encapsulate all of the shell logic into a single shell script and then execute "/bin/sh /path/to/file.sh"

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
  • If the `export` only needs to occur for the lifespan of the spawned process, @JimGarrison's comment above is more comprehensive. – tresf Mar 23 '16 at 18:33