首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java ()中运行git clone -在getRuntime.exec中使用/bin/bash -在错误流中“没有这样的文件或目录”

在Java ()中运行git clone -在getRuntime.exec中使用/bin/bash -在错误流中“没有这样的文件或目录”
EN

Stack Overflow用户
提问于 2020-12-23 15:54:29
回答 1查看 150关注 0票数 0

在Linux中,我正在尝试使用Java的Runtime.getRuntime().exec()来执行git clone,解释器是/bin/bash。但是,我在错误流中得到“没有这样的文件或目录”。我搜索了堆栈溢出,发现没有答案可以解决我的问题。下面是我用Test.java编写的程序:

代码语言:javascript
复制
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,得到了同样的结果。我得到的输出如下:

代码语言:javascript
复制
/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中失败。我该如何解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2020-12-23 16:09:00

您必须将-c作为单独的参数传递,并且不应在命令中添加文字双引号:

代码语言:javascript
复制
new String[]{ "bash", "-c", "git clone ..." }

这是因为空格和引号是shell语法,而Runtime.exec不会调用它们来运行命令(这恰好是shell调用,但这是无关的)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65420764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档