我正在尝试通过从 Java 传递参数变量来执行 shell 文件。
我想从java代码中调用shell文件script.sh,并传递上面的变量,如start、end、country。
int start = 10;
int end = 100;
String country = India;
String scriptlocation = scriptloc+"/script.sh";
ProcessBuilder processBuilder = new ProcessBuilder(scriptlocation);
processBuilder.environment().put("start", start);
processBuilder.environment().put("end", end);
processBuilder.environment().put("country", country);
其中开头和结尾是整数,国家/地区是字符串 变量..所以上面的方法不适用于int变量。
我也尝试过以下方法
ProcessBuilder pb2=new ProcessBuilder("/bin/sh",
"-c",
"start=start end=end country=country scriptlocation");
我不确定这个方法是否有效。因为它必须采用 10 、 100 和 india 等变量的值作为开始、结束和国家/地区变量。请建议。
最佳答案
put
用于设置环境变量而不是命令行参数(请参阅 shell 手册以了解什么是环境变量)。
您需要为每个参数传递一个字符串。传递 "/bin/sh", "-c", "start=start end=end Country=country scriptlocation"
使 shell 接收 3 个参数。此外,您还需要将 int
转换为字符串。
我不确切知道你的脚本如何接收它的参数,但类似这样的东西应该可以工作:
new ProcessBuilder( "/bin/sh", "-c", "start="+start, "end="+end, "country="+country, scriptlocation");
关于java - 从 java 传递 int 和 string 参数执行 shell 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785934/