从 Java 同步运行 shell 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20592397/
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
Run shell script from Java Synchronously
提问by user1295300
I am trying to execute a Bash Shell script from Java and it runs fine using this piece of code.
我正在尝试从 Java 执行 Bash Shell 脚本,并且使用这段代码运行良好。
public void executeScript() {
try {
new ProcessBuilder("myscript.sh").start();
System.out.println("Script executed successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
The above code runs fine asynchronously. But what I would like to achieve is to execute the code synchronously. I would like the Java process to wait until the execution of the script is completed and then execute the next batch of code.
上面的代码异步运行良好。但我想实现的是同步执行代码。我希望Java进程等到脚本执行完成后再执行下一批代码。
To summarize, I would like the "Print statement - Script executed successfully" to be executed afterthe batch file ("myscript.sh") completes execution.
总而言之,我希望在批处理文件(“myscript.sh”)完成执行后执行“打印语句 - 脚本执行成功” 。
Thanks
谢谢
采纳答案by Elliott Frisch
You want to wait for the Process to finish, that is waitFor()like this
你要等待 Process 完成,就是像这样的waitFor()
public void executeScript() {
try {
ProcessBuilder pb = new ProcessBuilder(
"myscript.sh");
Process p = pb.start(); // Start the process.
p.waitFor(); // Wait for the process to finish.
System.out.println("Script executed successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
回答by Jim Garrison
Use Process#waitFor()
to pause the Java code until the script terminates. As in
使用Process#waitFor()
暂停Java代码,直到脚本终止。如在
try {
Process p = new ProcessBuilder("myscript.sh").start();
int rc = p.waitFor();
System.out.printf("Script executed with exit code %d\n", rc);
回答by rgaut
The above code doesn't work if I wanted to move a file from one location to another, so I've fixed it with below code.
如果我想将文件从一个位置移动到另一个位置,上面的代码不起作用,所以我用下面的代码修复了它。
class Shell
{
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("/home/sam/myscript.sh");
Process p = pb.start(); // Start the process.
p.waitFor(); // Wait for the process to finish.
System.out.println("Script executed successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
myscript.sh
#!/bin/bash
mv -f /home/sam/Download/cv.pdf /home/sam/Desktop/