如何 运行 shell 使用 Java 存储在字符串变量中的脚本?
How to run shell script which is stored in a String variable using Java?
我需要在 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。
您需要用 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);
}
我需要在 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。
您需要用 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);
}