0

我正在尝试执行一个 bash 脚本,该脚本从 java 传递了 4 个参数。我可以使用以下代码完美地执行没有参数的脚本:

    try 
        {       
            String command = "bash bash/testbash.sh";
            Runtime run = Runtime.getRuntime();
            Process pr = run.exec(command);
            pr.waitFor();
            BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String line = "";
            while ((line=buf.readLine())!=null) 
            {
                System.out.println(line);
            }
         }  
        catch (Exception e) 
        {  
            System.out.println("Exception " + e);
            e.printStackTrace();
        }  
    }

所以我打算创建一个 String[] 来将命令和参数都传递给 Runtime.exec(),如下所示:

    try 
        {       
            String[] command ={"bash bash/testbash.sh"};
            Runtime run = Runtime.getRuntime();
            Process pr = run.exec(command);
            pr.waitFor();
            BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String line = "";
            while ((line=buf.readLine())!=null) 
            {
                System.out.println(line);
            }
         }  
        catch (Exception e) 
        {  
            System.out.println("Exception " + e);
            e.printStackTrace();
        }  
    }

这给了我这个错误:

Exception java.io.IOException: Cannot run program "bash bash/testbash.sh": error=2, No such file or directory
java.io.IOException: Cannot run program "bash bash/testbash.sh": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1042)
    at java.lang.Runtime.exec(Runtime.java:615)
    at java.lang.Runtime.exec(Runtime.java:483)
    at bashExecuter.main(bashExecuter.java:43)
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:1023)
    ... 3 more

这对我来说毫无意义。bash 文件显然存在,因为我只是将它与 String 命令一起使用,但是当我将相同的东西与 String[] 命令一起使用时,它不存在吗?我将如何传递带有参数的命令?

4

1 回答 1

1

字符串[] 命令 ={"bash bash/testbash.sh"};

String[] command ={"bash", "bash/testbash.sh"};
于 2013-05-24T01:21:46.747 回答