在java getruntime.exec()中运行git clone—在linux中使用/bin/bash—在错误流中“没有这样的文件或目录”

eaf3rand  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(689)

我正在尝试使用linux中的java的runtime.getruntime().exec()在java中执行git clone,解释器是/bin/bash。但是,我在错误流中得到“没有这样的文件或目录”。我搜索了stackoverflow,发现没有答案可以解决我的问题。下面是我在test.java中的程序:

import java.io.*;
public class Test {
    public static void main(String[] args) throws IOException, InterruptedException {
        String version = "10.1.1";
        String repo_url = "https://github.com/postcss/postcss-url";
        String directory = "./tmp";
        String cmd = "\"/usr/bin/git clone --branch " + version + " " + repo_url + " --depth=1 " + directory + "\"";
        // String cmd = "git -h";
        String interpreter = "/bin/bash";
        cmd = " -c "+ cmd;
        System.out.println(interpreter + cmd);
        Process process = Runtime.getRuntime().exec(new String[]{ interpreter, cmd });
        print(process.getInputStream());
        print(process.getErrorStream());
        process.waitFor();
        int exitStatus = process.exitValue();
        System.out.println("exit status: " + exitStatus);
        File[] files = new File(directory).listFiles();
        System.out.println("number of files in the directory: " + files.length);
    }

    public static void print(InputStream input) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader bf = new BufferedReader(new InputStreamReader(input));
                String line = null;
                try {
                    while ((line = bf.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (IOException e) {
                    System.out.println("IOException");
                }
            }
        }).start();
    }
}

./tmp肯定是一个空目录。我用 javac Test.java 编译代码然后运行 java Test . 另外,我试过了 sudo java Test 得到了同样的结果。我得到如下输出:

/bin/bash -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp"
exit status: 127
/bin/bash:  -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp": No such file or directory
Exception in thread "main" java.lang.NullPointerException
        at Test.main(Test.java:18)

当我使用“git-h”或“ls”时,它工作得很好。但是,这个命令 /bin/bash -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp" 在shell中工作,但在java中失败。我怎样才能解决这个问题?

cu6pst1q

cu6pst1q1#

你必须通过 -c 作为一个单独的参数,您不应该在命令中添加双引号:

new String[]{ "bash", "-c", "git clone ..." }

这是因为空格和引号是shell语法 Runtime.exec 不调用一个来运行命令(这恰好是一个shell调用,但这是不相关的)

相关问题