如何使用Java运行存储在String变量中的shell脚本?

时间:2015-09-10 02:26:40

标签: java bash shell runtime processbuilder

我需要在Java中执行shell脚本。我的shell脚本不在文件中,它实际上存储在String变量中。我从其他一些应用程序中获取了我的shell脚本详细信息。

我知道如何在Java中执行不同的命令,如下所示:

public static void main(final String[] args) throws IOException, InterruptedException {
    //Build command 
    List<String> commands = new ArrayList<String>();
    commands.add("/bin/cat");
    //Add arguments
    commands.add("/home/david/pk.txt");
    System.out.println(commands);

    //Run macro on target
    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(new File("/home/david"));
    pb.redirectErrorStream(true);
    Process process = pb.start();

    //Read output
    StringBuilder out = new StringBuilder();
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null, previous = null;
    while ((line = br.readLine()) != null)
        if (!line.equals(previous)) {
            previous = line;
            out.append(line).append('\n');
            System.out.println(line);
        }

    //Check result
    if (process.waitFor() == 0) {
        System.out.println("Success!");
        System.exit(0);
    }

    //Abnormal termination: Log command parameters and output and throw ExecutionException
    System.err.println(commands);
    System.err.println(out.toString());
    System.exit(1);
}

就我而言,我将在json字符串变量中包含脚本信息,我将从中提取脚本内容:

{"script":"#!/bin/bash\n\necho \"Hello World\"\n"}

下面是我从json上面提取脚本内容的代码,现在我不知道如何执行此脚本并将一些参数传递给它。现在,我可以传递任何简单的字符串参数:

String script = extractScriptValue(path, "script"); // this will give back actual shell script

// now how can I execute this shell script using the same above program?
// Also how I can pass some parameters as well to any shell script?

执行上述脚本后,应该打印出Hello World。

1 个答案:

答案 0 :(得分:1)

您需要使用shell启动Process,然后将脚本发送到其输入流。以下只是概念验证,您需要更改一些内容(例如使用ProcessBuilder创建流程):

public static void main(String[] args) throws IOException, InterruptedException {

    // this is your script in a string
    String script = "#!/bin/bash\n\necho \"Hello World\"\n echo $val";

    List<String> commandList = new ArrayList<>();
    commandList.add("/bin/bash");

    ProcessBuilder builder = new ProcessBuilder(commandList);
    builder.environment().put("val", "42");
    builder.redirectErrorStream(true);
    Process shell = builder.start();

    // Send your script to the input of the shell, something
    // like doing cat script.sh | bash in the terminal
    try(OutputStream commands = shell.getOutputStream()) {
        commands.write(script.getBytes());
    }

    // read the outcome
    try(BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()))) {
        String line;
        while((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }

    // check the exit code
    int exitCode = shell.waitFor();
    System.out.println("EXIT CODE: " + exitCode);
}