Mike
Mike

Reputation: 2376

Run bash scripts from JAVA and return the results

I am attempting to get output of a shell / bash script, that is run from a JAVA program, although I am not having much luck, the code is as follows:

GetStats(winhostname);

public static String winhostname "cmd /c hostname";

public static void GetStats(String operation)
    {
         try 
            { 
            Process p=Runtime.getRuntime().exec(operation); 
            p.waitFor(); 
            BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
            String line=reader.readLine(); 
            while(line!=null) 
            { 
            System.out.println(line);
            if (operation.equals("winhostname"))
            {
                winhostnamevalue = line;
            }
            line=reader.readLine(); 
            } 

            } 
            catch(IOException e1) {} 
            catch(InterruptedException e2) {}       
    }

This works on Windows fine, so I changed the value of winhostname to "sh namecheck.sh" (which simply echos the hostname) and the shell script is located in the same directory as the java / class file. Although when run I get a blank result, not null, just blank.

Upvotes: 2

Views: 2084

Answers (1)

AlexR
AlexR

Reputation: 115328

Try /bin/sh. I do not sure that when you are running program from java it has all environment that you have when you are working with shell.

If it does not work try to run some command (e.g. pwd). But provide full path. Then, when it works try your command again and be sure that it can find your script. For the beginning use absolute path. Then move to relative path.

Good luck.

Upvotes: 1

Related Questions