简体   繁体   English

如何在 Java 中执行 shell 脚本

[英]How to execute a shell script in Java

I have to run a shell script from Java in a Linux box for eg, Below is the script path and all parameters needed by the script.我必须在 Linux 机器中从 Java 运行 shell 脚本,例如,下面是脚本路径和脚本所需的所有参数。

"ksh /xyz/abc/data/code_base/RUN_SCRIPTS/dev/my_script.sh param1 param2 20200901 459 121"

Below is the code,下面是代码,

String script = "ksh /xyz/abc/data/code_base/RUN_SCRIPTS/dev/my_script.sh param1 param2 20200901 459 121";
ProcessBuilder processBuilder = new ProcessBuilder();                       
processBuilder.command(script);
processBuilder.redirectErrorStream(true);
//start() will be in try catch
process = processBuilder.start();

int exitVal = process.waitFor();

if(exitVal == 0){
   //code
}

Do i need to pass the script as a List by adding each as a separate String in the List ?我是否需要通过将每个脚本作为单独的字符串添加到列表中来将脚本作为列表传递? "ksh" , "/xyz/abc/data/code_base/RUN_SCRIPTS/dev/my_script.sh" , "param1" "param2" "20200901" "459" "121" "ksh", "/xyz/abc/data/code_base/RUN_SCRIPTS/dev/my_script.sh", "param1" "param2" "20200901" "459" "121"

On my Windows machine, i am opening a Notepad as below and it works fine,在我的 Windows 机器上,我正在打开一个记事本,如下所示,它工作正常,

ProcessBuilder processBuilder = new ProcessBuilder("Notepad.exe", "C:/Dev/Test.txt");
processBuilder.redirectErrorStream(true);
process = processBuilder.start();

Will the script get executed on the Linux box properly or any more changes are required in the code ??脚本会在 Linux 机器上正确执行还是需要对代码进行更多更改?

You should be able to use Runtime.exec() or ProcessBuilder to invoke a shell to run a script, but the whole process is full of pitfalls.应该能够使用Runtime.exec()ProcessBuilder来调用 shell 来运行脚本,但是整个过程充满了陷阱。

I would suggest reading this article:我建议阅读这篇文章:

https://www.infoworld.com/article/2071275/when-runtime-exec---won-t.html https://www.infoworld.com/article/2071275/when-runtime-exec---won-t.html

which explains many of these pitfalls, and how to avoid them.这解释了其中的许多陷阱,以及如何避免它们。 In particular, on Linux you'll almost certainly need to consume stdout and stderr from your shell invocation -- that's sometimes true even if the script doesn't produce any output.特别是,在 Linux 上,您几乎肯定需要从 shell 调用中使用 stdout 和 stderr —— 即使脚本不产生任何输出,有时也是如此。 You'll also need to be careful how you handle spaces and special characters -- if there are any -- in the arguments to your script.您还需要小心处理脚本参数中的空格和特殊字符(如果有的话)。 The parser that Java uses for the command line blindly breaks a command line at whitespace. Java 用于命令行的解析器盲目地在空格处中断命令行。

看看这个 Runtime.getRunTime().exec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM