I have a shell script with one parameter, as follow:
test.sh
#!/bin/bash
echo "Shell Demo";
echo "Hello $0";
Now I want to execute this script using ProgressBuilder and pass parameters. The java code as follow:
public void testShell() throws Exception {
String shPath = "./test.sh";
// want to pass a value "Jack" to shell script
ProcessBuilder builder = new ProcessBuilder(shPath, "Jack");
Process result = builder.start();
result.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(result.getInputStream()));
String output;
while ((output = stdInput.readLine()) != null) {
System.out.println(output);
}
}
Output:
Shell Demo
Hello ./test.sh
The output I want is:
Shell Demo
Hello Jack
You're going to want to remove that result.waitFor
and also specify the executor to use, ie) bash (you can also use sh), other than that you're on the right path.
public String[] createExecutionString(String process, String...params) {
final List<String> executor = new ArrayList<>();
executor.add("bash"); /* cmd on windows */
executor.add("-c"); /* /c on windows */
executor.add(process);
for (String param : params) {
executor.add(param);
}
return executor.toArray(new String[0]);
}
public void testShell() throws Exception {
String shPath = "./test.sh";
// want to pass a value "Jack" to shell script
ProcessBuilder builder = new ProcessBuilder(createExecutionString(shPath, "Jack"));
Process result = builder.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(result.getInputStream()));
String output;
while ((output = stdInput.readLine()) != null) {
System.out.println(output);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.