Darryl Bayliss
Darryl Bayliss

Reputation: 2712

Running UNIX Source command in Java

This is my first question on stackoverflow so I'll try to keep it concise and relevant.

I'm currently creating a Java program that is attempting to call an external program located on the system, in order to do this however I am required to call a shell script that sets up links to the relevant libraries to ensure that the system is linked to these before the external program can be executed.

The issue at hand is that I cannot invoke the shell script through Java, I've researched high and low and am aware that of alternative ways such as the use of the ProcessBuilder class. Unfortunately I'm quite new to the world of trying to invoke command line statements through Java and so I'm stuck for answers.

An example of the code I am using can be found below:

private void analyse_JButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                

// Get project path for copying of Fortran program to folder and execution

String projectPath =  Newproject_GUI.getProjectPath();


String sourcePath [] = {"/bin/sh ", "-c ","source ~/set_env_WRF_gnu.sh"} ;



Runtime fortranAnalyser = Runtime.getRuntime();

try {
        Process p = fortranAnalyser.exec("cp main.exe " + projectPath);
        Process k = fortranAnalyser.exec(sourcePath);



        BufferedReader is = new BufferedReader(new InputStreamReader(k.getInputStream()));
        String line;
        while ((line = is.readLine()) != null) {

            System.out.println(line); 
        } 


    } catch (IOException ex) {
        Logger.getLogger(Analyser_GUI.class.getName()).log(Level.SEVERE, null, ex);
      }

}

Process p works fine and does indeed copy main.exe to the intended directory when the method is called. Process k however does not and this is where the issue is.

Thanks in advance.

Upvotes: 4

Views: 2018

Answers (1)

lzap
lzap

Reputation: 17174

The issue is "source" is internal command of BASH (you are using "sh" but that is just BASH in the simplified mode). So what you do is:

  • you spawn new process "sh" and source something there (setting some VARIABLES I guess)
  • the process ends and all VARIABLES are lost
  • you spawn another process, but VARIABLES are already gone

I am not sure if you use those variables later on, but according to the script name it is probably setting some. Don't do that like this.

By the way if you only want to execute script in bash, you don't need to source it. To get it's side effects, just execute it with:

String sourcePath [] = {"/bin/sh ", "/home/XYZ/set_env_WRF_gnu.sh"} ;

Please note you cannot use ~ in this case, use Java to get your home dir.

Upvotes: 3

Related Questions