how to launch a shell script in a new gnome termin

2019-09-02 12:55发布

问题:

I'm trying to run a shell script (say myscript.sh) from a java program.

when i run the script from terminal, like this :

./myscript.sh

it works fine.

But when i call it from the java program, with the following code :

try
    {
        ProcessBuilder pb = new ProcessBuilder("/bin/bash","./myScript.sh",someParam);

        pb.environment().put("PATH", "OtherPath");

        Process p = pb.start(); 

        InputStreamReader isr = new InputStreamReader(p.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String line ;
        while((line = br.readLine()) != null)
           System.out.println(line);

        int exitVal = p.waitFor();
    }catch(Exception e)
    {  e.printStackTrace();  }
}

It doesnt goes the same way. Several shell commands (like sed, awk and similar commands) get skipped and donot give any output at all.

Question : Is there some way to launch this script in a new terminal using java.

PS : i've found that "gnome-terminal" command launches a new terminal in shell, But, i'm unable to figure out, how to use the same in a java code.

i'm quite new to using shell scripting. Please help

Thanks in advance

回答1:

In java:

import java.lang.Runtime;                                                        

class CLI {                                                                      

    public static void main(String args[]) {                                     
        String command[] = {"/bin/sh", "-c", 
                            "gnome-terminal --execute ./myscript.sh"};
        Runtime rt = Runtime.getRuntime();                                       
        try {                                                                    
            rt.exec(command);                                                    
        } catch(Exception ex) {                                                  
            // handle ex                                                         
        }                                                                        
    }                                                                            

}

And the contents of the script are:

#!/bin/bash    

echo 'hello!'    

bash

Notes:

  • You'll do this in a background thread or a worker
  • The last command, in the shell script, is bash; otherwise execution completes and the terminal is closed.
  • The shell script is located in the same path as the calling Java class.


回答2:

Don't overrwrite your entire PATH...

pb.environment().put("PATH", "OtherPath"); // This drops the existing PATH... ouch.

Try this instead

pb.environment().put("PATH", "OtherPath:" + pb.environment().get("PATH"));

Or, use the full directories to your commands in your script file.



回答3:

You must set your shell script file as executable first and then add the below code,

shellScriptFile.setExecutable(true);

//Running sh file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_SHELL_SCRIPT_FILE+File.separator+shellScriptFile.getName());                                                              
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);                              
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
    System.out.println("Shell script executed properly");
}


回答4:

This worked for me on Ubuntu and Java 8

 Process pr =new ProcessBuilder("gnome-terminal", "-e", 
                  "./progrm").directory(new File("/directory/for/the/program/to/be/executed/from")).start();

The previous code creates a new terminal in a specificied directory and executes a command



回答5:

script.sh Must have executable permissions

     public class ShellFileInNewTerminalFromJava {

        public static void main(String[] arg) {

    try{
    Process pr =new ProcessBuilder("gnome-terminal", "-e", "pathToScript/script.sh").start();
    }catch(Exception e){
        e.printStackTrace();
    }
    }
} 


标签: java bash shell