1

I am having a bash script file which I am calling using the source command in a shell and is setting a number of environment variables. Then I can use all the tools the environment variables are setting.

Now I want to do the same in Java by the use of:

static Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);
pr.waitFor();

I know that source is an internal command and I can not call it from Java.

Is there any other way to set the enviroment variable in that file from java in order to be able to use them in my code later for calling other commands?

Thank you in advance!

Kyriakos
  • 757
  • 8
  • 23

1 Answers1

3
Process pr = new ProcessBuilder("/bin/bash", "-c", ". env.sh; " + command).start();

Try something like this, where you both source the script and execute a subsequent command in the same shell process. Effectively you source the script every time you want to execute a command.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Sorry but I am new to this stuff. So After creating the process pr, how am I executing it using my runtime? – Kyriakos Aug 22 '13 at 15:10
  • @Kyriakos In the example above it is executing because of the .start() at the end. You can create the processbuilder before like this: Processbuilder pb = new ProcessBuilder("/bin/bash", "-c", ". env.sh; " + command); and then execute it with: Process p= pb.start(); – Miterion Aug 22 '13 at 15:15
  • I did something like this: String sourcePath [] = {"/bin/bash", "-c", xmosSetEnvCmd + ";" + xcoreCompileCmd}; Then pr =run.exec(sourcePath); and then pr.waitFor(); Which I think is the same! Thank you very much Miterion! Its working – Kyriakos Aug 22 '13 at 15:24
  • @Kyriakos [`ProcessBuilder` is preferable to `Runtime.exec()`](http://stackoverflow.com/questions/5886829/processbuilder-vs-runtime-exec), IMO. It has a better API, and `Runtime.exec()` is actually implemented using `ProcessBuilder` under the covers. – John Kugelman Aug 22 '13 at 15:27
  • Is there a reason for that John? – Kyriakos Aug 22 '13 at 15:28