如何从 Java 代码运行 Unix shell 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/525212/
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
How to run Unix shell script from Java code?
提问by
It is quite simple to run a Unix command from Java.
从 Java 运行 Unix 命令非常简单。
Runtime.getRuntime().exec(myCommand);
But is it possible to run a Unix shell script from Java code? If yes, would it be a good practice to run a shell script from within Java code?
但是是否可以从 Java 代码运行 Unix shell 脚本?如果是,从 Java 代码中运行 shell 脚本是一个好习惯吗?
回答by Chris Ballance
I think you have answered your own question with
我想你已经回答了你自己的问题
Runtime.getRuntime().exec(myShellScript);
As to whether it is good practice... what are you trying to do with a shell script that you cannot do with Java?
至于它是否是好的做法......你想用一个你不能用Java做的shell脚本做什么?
回答by Hyman Leow
I would say that it is not in the spirit of Javato run a shell script from Java. Java is meant to be cross platform, and running a shell script would limit its use to just UNIX.
我会说从 Java 运行 shell 脚本不符合 Java 的精神。Java 是跨平台的,运行 shell 脚本会限制它只在 UNIX 上使用。
With that said, it's definitely possible to run a shell script from within Java. You'd use exactly the same syntax you listed (I haven't tried it myself, but try executing the shell script directly, and if that doesn't work, execute the shell itself, passing the script in as a command line parameter).
话虽如此,绝对可以从 Java 中运行 shell 脚本。您将使用与您列出的完全相同的语法(我自己没有尝试过,但尝试直接执行 shell 脚本,如果这不起作用,请执行 shell 本身,将脚本作为命令行参数传入) .
回答by Kekoa
It is possible, just exec it as any other program. Just make sure your script has the proper #! (she-bang) line as the first line of the script, and make sure there are execute permissions on the file.
这是可能的,只需像任何其他程序一样执行它即可。只需确保您的脚本具有正确的 #! (she-bang) 行作为脚本的第一行,并确保该文件具有执行权限。
For example, if it is a bash script put #!/bin/bash at the top of the script, also chmod +x .
例如,如果它是一个 bash 脚本,将 #!/bin/bash 放在脚本的顶部,也 chmod +x 。
Also as for if it's good practice, no it's not, especially for Java, but if it saves you a lot of time porting a large script over, and you're not getting paid extra to do it ;) save your time, exec the script, and put the porting to Java on your long-term todo list.
另外,至于它是否是好的做法,不,它不是,尤其是对于 Java,但是如果它为您节省了大量移植大型脚本的时间,并且您没有获得额外的报酬;) 节省您的时间,执行脚本,并将移植到 Java 放在您的长期待办事项列表中。
回答by Milhous
You should really look at Process Builder. It is really built for this kind of thing.
你真的应该看看Process Builder。它真的是为这种事情而建的。
ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();
回答by Saul
Just the same thing that Solaris 5.10 it works like this ./batchstart.sh
there is a trick I don′t know if your OS accept it use \\. batchstart.sh
instead. This double slash may help.
与 Solaris 5.10 一样,它的工作原理是这样的./batchstart.sh
,我不知道您的操作系统是否接受它,\\. batchstart.sh
而是使用一个技巧。这个双斜线可能会有所帮助。
回答by Vladimir Bosyi
As for me all things must be simple. For running script just need to execute
至于我,一切都必须简单。对于运行脚本只需要执行
new ProcessBuilder("pathToYourShellScript").start();
回答by Desta Haileselassie Hagos
Yes it is possible to do so. This worked out for me.
是的,可以这样做。这对我有用。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.InputStream;
public static void readBashScript() {
try {
Process proc = Runtime.getRuntime().exec("/home/destino/workspace/JavaProject/listing.sh /"); //Whatever you want to execute
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
回答by DayaMoon
I think with
我认为与
System.getProperty("os.name");
Checking the operating system on can manage the shell/bash scrips if such are supported. if there is need to make the code portable.
如果支持,检查操作系统可以管理 shell/bash 脚本。如果需要使代码可移植。
回答by Not a bug
You can use Apache Commons exec libraryalso.
您也可以使用Apache Commons exec 库。
Example :
例子 :
package testShellScript;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
public class TestScript {
int iExitValue;
String sCommandString;
public void runScript(String command){
sCommandString = command;
CommandLine oCmdLine = CommandLine.parse(sCommandString);
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(oCmdLine);
} catch (ExecuteException e) {
System.err.println("Execution failed.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("permission denied.");
e.printStackTrace();
}
}
public static void main(String args[]){
TestScript testScript = new TestScript();
testScript.runScript("sh /root/Desktop/testScript.sh");
}
}
For further reference, An example is given on Apache Docalso.
为了进一步参考,Apache Doc 上也给出了一个示例。
回答by Girdhar Singh Rathore
String scriptName = PATH+"/myScript.sh";
String commands[] = new String[]{scriptName,"myArg1", "myArg2"};
Runtime rt = Runtime.getRuntime();
Process process = null;
try{
process = rt.exec(commands);
process.waitFor();
}catch(Exception e){
e.printStackTrace();
}