【问题标题】:java run bash script, command not foundjava运行bash脚本,找不到命令
【发布时间】:2016-09-27 13:52:50
【问题描述】:

我尝试使用 java 来运行一些 bash 脚本并将终端输出存储在一个字符串中。但是,有很多命令不能以这种方式工作。它一直显示找不到命令,但我可以在终端中正确运行这些命令,ex node --version,go --version。我猜是路径问题,但不知道如何解决。

另一个问题,当我运行“python --version”时,它显示“Python 2.7.10”,但它在 getErrorStream 中。谁能给我一些提示?

public static void runscript() throws IOException {
    Runtime rt = Runtime.getRuntime();
    String[] commands = { "/bin/bash", "-c", "node --version" };
    Process proc = null;
    try {
        proc = rt.exec(commands);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }

    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
}

【问题讨论】:

  • 您能否尝试提供命令的完整路径而不仅仅是名称。 “哪个节点”会给你路径。尝试在您的 java 代码中使用它。同样值得从 java 中回显 $PATH 以查看与终端的区别
  • 关于“getErrorStream”:如您所知,程序可以使用两个流来打印信息。程序本身决定使用哪一个。尽管有相当多的官方指导在哪里打印什么,但这通常没有准确处理。在你的情况下,python 显然是这样做的......
  • @VishalKamat 我在下面回复它。感谢您的精彩和有用的评论!
  • @EagleRainbow 我不知道。我以为这是我喜欢的路径设置错误。感谢分享。

标签: java bash scripting command


【解决方案1】:

回复@VishalKamat 评论。
当我尝试使用“哪个节点”的输出作为我的路径时,即“/usr/local/bin/node”。有效!!!
但是,这是否意味着当我需要获取不同的应用程序版本信息时,我必须更改路径? 我以为我可以像在终端中一样轻松获取信息。

我尝试用这种方式通过java打印$PATH

String[] commands = { "/bin/bash","-c", "$PATH" };

错误信息是:

/bin/bash: /usr/bin:/bin:/usr/sbin:/sbin: No such file or directory

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 2017-08-10
    • 2019-04-15
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    相关资源
    最近更新 更多