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!

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Sorry but I am new to this stuff. So After creating the process pr, how am I executing it using my runtime?
@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();
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 ProcessBuilder is preferable to Runtime.exec(), IMO. It has a better API, and Runtime.exec() is actually implemented using ProcessBuilder under the covers.
Is there a reason for that John?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.