1
我需要在Java中執行一個shell腳本。我的shell腳本不在文件中,它實際上存儲在一個String變量中。我從其他應用程序獲取我的shell腳本細節。如何運行使用Java存儲在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。
謝謝您的建議。你能告訴我一個例子嗎,我怎樣在這裏使用'ProcessBuilder'?我從來沒有使用過這些API,因此感到困惑。我剛剛在你的建議中添加了一個ProcessBuilder,不知何故它不適用於我。我沒有看到「Hello World」輸出被打印出來。 – user1950349
編輯使用的ProcessBuilder代替 – morgano
順便說一句,你是明確的打印輸出外殼(使用過程'OutputStream')只是雙重檢查,你是沒想到的是,輸出將不無爲 – morgano