带参数的runtime exec方法不会在Java中运行bash脚本

时间:2015-02-13 20:33:55

标签: java bash

我有以下两种情况。我使用带有参数的Runtime.getRuntime()。exec方法的一个似乎不起作用我在运行bash脚本时遇到错误。

但是,如果我使用exec方法而不将任何值传递给exec参数则可以正常工作。

String cfenv_location="bash /root/.cfenv/environments/ussouth_ys1/bin/cf ";
Process p = Runtime.getRuntime().exec(new String[]{cfenv_location, "create-service", servicename, planname, appname.replaceAll(" ", "-")});

错误:

exception happened - here's what I know:
java.io.IOException: Cannot run program "bash /root/.cfenv/environments/ussouth_ys1/bin/cf": error=2, No such file or directory
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
        at java.lang.Runtime.exec(Runtime.java:617)
        at java.lang.Runtime.exec(Runtime.java:485)
        at JavaRunCommand.cfCreateService(JavaRunCommand.java:111)
        at JavaRunCommand.main(JavaRunCommand.java:359)
Caused by: java.io.IOException: error=2, No such file or directory
        at java.lang.UNIXProcess.forkAndExec(Native Method)
        at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
        at java.lang.ProcessImpl.start(ProcessImpl.java:130)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
        ... 4 more

作品

String cfenv_location="bash /root/.cfenv/environments/ussouth_ys1/bin/cf ";
String command = cfenv_location+"login -a "+urllocation+ " -u "+username+ " -p "+password+ " -o "+org+" -s "+space;
Process p = Runtime.getRuntime().exec(command);

1 个答案:

答案 0 :(得分:1)

消息:

Cannot run program "bash /root/.cfenv/environments/ussouth_ys1/bin/cf"

表明,该String被解释为命令而不是命令和参数(用空格字符分隔)。

正确的方法是拆分字符串并将其称为

Runtime.getRuntime().exec(new String[]{"bash", cfenv_location, ...

其中cfenv_location没有启动"base "部分......