从 Java 代码运行 shell 脚本并传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12812345/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:19:04  来源:igfitidea点击:

Running shell script from java code and pass arguments

javashellruntime.execshell-exec

提问by Lolly

I am executing a shell script from Java program. I have implemented it using Runtime class. Below is the code I implemented

我正在从 Java 程序执行 shell 脚本。我已经使用 Runtime 类实现了它。下面是我实现的代码

final StringBuilder sb = new StringBuilder("test.sh");
sb.append("/path to/my/text file");

final Process p = Runtime.getRuntime().exec(sb.toString());

Here sb is string buffer object where I append my parameters and use it in exec method. But the problem is the parameter I pass "/path to/my/text file" is considered as 4 parameters

这里 sb 是字符串缓冲区对象,我在其中附加参数并在 exec 方法中使用它。但问题是我传递的参数“/path to/my/text file”被认为是 4 个参数

/path
 to
/my/text
 file

But if run in shell as test.sh "/path to/my/text file" which is taken as single parameter. How can I achieve the same using Java code, where I need to consider this path with spaces as single argument. Any please will be really appreciable.

但是如果在 shell 中作为 test.sh "/path to/my/text file" 运行,它被当作单个参数。如何使用 Java 代码实现相同的目标,我需要将此路径与空格视为单个参数。任何请都会非常可观。

回答by MadProgrammer

Use ProcessBuilder, it's what it's designed for, to make your life easier

使用ProcessBuilder,这就是它的设计目的,让您的生活更轻松

ProcessBuilder pb = new ProcessBuilder("test.sh", "/path", "/my/text file");
Process p = pb.start();

回答by Sumit Singh

Use this:

用这个:

final StringBuilder sb = new StringBuilder("test.sh");
sb.append(" \"/path to/my/text file\"");

回答by FThompson

To recreate the command you run in shell manually, test.sh "/path to/my/text file", you will need to include the quotes.

要重新创建您在 shell 中手动运行的命令test.sh "/path to/my/text file",您需要包含引号。

final StringBuilder sb = new StringBuilder("test.sh");
sb.append(" \"/path to/my/text file\""); //notice escaped quotes
final Process p = Runtime.getRuntime().exec(sb.toString());

回答by Anshu

Your approach is correct you just need to add a space (" ")before parameters and escape the "/" and " "characters in the parameters

您的方法是正确的,您只需要space (" ")在参数之前添加一个并转义参数中的"/" and " "字符