简体   繁体   English

如何向在 Java 中调用的 bash 脚本添加参数?

[英]How can I add arguments to my bash script called in Java?

i'm trying to find a way to add any number of argument to a bash script called in java language.我正在尝试找到一种方法,将任意数量的参数添加到用 Java 语言调用的 bash 脚本中。 When I call a script without arguments it works just fine, but the moment I try to add arguments it skips the script and end the application.当我调用不带参数的脚本时,它工作得很好,但是当我尝试添加参数时,它会跳过脚本并结束应用程序。 The getName function returns the name of the script. getName函数返回脚本的名称。

Here is the function called to execute the script :这是调用执行脚本的函数:

    String cmd = Paths.get("").toAbsolutePath().toString()+"/"+getName();
    Process p;

    try{
        p = Runtime.getRuntime().exec(new String[]{"/bin/sh",cmd});
        p.waitFor();
        p.destroy();
    }catch (Exception e) {}

And here is where I create the script (I put the function above in the constructor of the Script class)这是我创建脚本的地方(我将上面的函数放在 Script 类的构造函数中)

new Script("script_name",new String[]{argument1,argument2});

from Javadoc I would change the line to:从 Javadoc 我会将这一行更改为:

p = Runtime.getRuntime().exec(new String[]{"/bin/sh",cmd, argument1,argument2 });

It says:它说:

"cmdarray - array containing the command to call and its arguments." “cmdarray - 包含要调用的命令及其参数的数组。”

Which means the String array consists of the command and all the parameters.这意味着字符串数组由命令和所有参数组成。

http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#exec-java.lang.String:A- http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#exec-java.lang.String:A-

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

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