简体   繁体   English

如何通过Java程序在新的gnome终端中启动Shell脚本

[英]how to launch a shell script in a new gnome terminal, from a java program

I'm trying to run a shell script (say myscript.sh) from a java program. 我正在尝试从Java程序运行Shell脚本(例如myscript.sh)。

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 : 但是当我从Java程序调用它时,代码如下:

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. 几个shell命令(如sed,awk和类似命令)被跳过,根本不提供任何输出。

Question : Is there some way to launch this script in a new terminal using java. 问题:有什么方法可以使用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. PS:我发现“ gnome-terminal”命令在shell中启动了一个新终端,但是,我无法弄清楚如何在Java代码中使用它。

i'm quite new to using shell scripting. 我对使用Shell脚本非常陌生。 Please help 请帮忙

Thanks in advance 提前致谢

In java: 在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 ; shell脚本中的最后一个命令是bash otherwise execution completes and the terminal is closed. 否则执行完成并且终端关闭。
  • The shell script is located in the same path as the calling Java class. Shell脚本与调用Java类位于同一路径。

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. 或者,在脚本文件中对命令使用完整目录。

You must set your shell script file as executable first and then add the below code, 您必须先将Shell脚本文件设置为可执行文件 ,然后添加以下代码,

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");
}

This worked for me on Ubuntu and Java 8 这在Ubuntu和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 上面的代码创建一个specificied目录中一个 新的终端并执行命令

script.sh Must have executable permissions script.sh必须具有可执行权限

     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();
    }
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM