bash 从 java 代码运行 shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49558546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:52:15  来源:igfitidea点击:

Run shell script from java code

javabashshell

提问by John123

I have a java app that runs a bash file and inside the bash file i have a code to run another java app and it doesn't seem to work.I come from c++ where this is a very easy task but i'm not really experienced in java. So, here's my code:

我有一个运行 bash 文件的 java 应用程序,在 bash 文件中我有一个代码来运行另一个 java 应用程序,但它似乎不起作用。我来自 c++,这是一项非常简单的任务,但我不是真的有java经验。所以,这是我的代码:

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class start {

public void executeScript(){
    try{
        ProcessBuilder pb = new ProcessBuilder("/root/Desktop/chat/script.sh");
        Process p = pb.start();
        p.waitFor();
        System.out.println("Script executed..");
    }catch(Exception e){
        e.printStackTrace();
        }

}

public static void main(String[] args) {
    start st = new start();
    System.out.println("I'm main..");
    st.executeScript();
}

}

Here's my bash file:

这是我的 bash 文件:

#!/bin/bash
echo "bash started"
java Client ip_address
echo "bash finished"

Here's the result of this code:

这是这段代码的结果:

I'm main.. Script executed..

我是主要的.. 脚本已执行..

I know "Script executed.." shouldn't print because the java file i'm trying to run from the bash file is an infinite loop.

我知道“脚本执行..”不应该打印,因为我试图从 bash 文件运行的 java 文件是一个无限循环。

Note:If i run the bash file separately in the terminal i get an infinite loop which is the intended result and this is why i know that my mistake is from this file.

笔记:If i run the bash file separately in the terminal i get an infinite loop which is the intended result and this is why i know that my mistake is from this file.

I hope I made myself clear and if not please ask for more information. Thank you.

我希望我说清楚了,如果没有,请询​​问更多信息。谢谢你。

回答by Jeffin Manuel

Another way of doing would be to use Runtime.getRuntime(). Something like this

另一种做法是使用Runtime.getRuntime(). 像这样的东西

  public void executeScript() throws IOException, InterruptedException {
    Process p = Runtime.getRuntime().exec("sh /root/Desktop/chat/script.sh");
    p.waitFor();

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));


    String line = "";
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

    line = "";
    while ((line = errorReader.readLine()) != null) {
        System.out.println(line);
    }
}

回答by Abhijit Pritam Dutta

With the above test you can not guaranty that whether it is running or not. Because clearly you told that your are running a infinite loop inside your second java application. Now my advise would be to put some System.out.printlnstatement inside that infinite loop and use below java code to execute your shell script. Here in the output.txtfile you can see the output from your shell script as well as java program and you will know whether application executed successfully or not. Also put some echostatement inside your shell script as well.

通过上述测试,您无法保证它是否正在运行。因为您清楚地告诉过您正在第二个 Java 应用程序中运行无限循环。现在我的建议是System.out.println在无限循环中放入一些语句,并使用下面的 java 代码来执行你的 shell 脚本。在output.txt文件中,您可以看到 shell 脚本和 java 程序的输出,您将知道应用程序是否成功执行。还要echo在您的 shell 脚本中放入一些语句。

 String[] command ={"/root/Desktop/chat/script.sh", "command line param if any"};
    ProcessBuilder pb = new ProcessBuilder(command);

    pb.redirectOutput(new File("/tmp/output.txt"));
    String result;
    String overall="";
    try {
        Process p = pb.start();
        p.waitFor();
        BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((result = br.readLine()) != null){
                overall = overall + "\n" + result;
            }
            p.destroy();
            System.out.println(result);

    } catch (Exception e) {
        e.printStackTrace();
    }

回答by Joonsun Baek

if you start a process like you wrote Process p = pb.start();it will make(we usually say fork) one more process from the java process.

如果你像你写的那样启动一个进程,Process p = pb.start();它会让(我们通常说 fork)从 java 进程中再创建一个进程。

  1. for example, java is running as a process 'A'
  2. and if the process 'A' starts another process 'B'
  3. then those are running at the same time.

    (in your case, A is 'JAVA' and B is 'Shell')

  1. 例如,java作为进程'A'运行
  2. 如果进程“A”启动另一个进程“B”
  3. 然后那些同时运行。

    (在您的情况下,A 是“JAVA”,B 是“Shell”)

so, it will be 2. and the 2 processes are running in the same time (parallely), so you will get two of those results at the same time.

因此,它将是 2. 并且 2 个进程同时(并行)运行,因此您将同时获得其中两个结果。