简体   繁体   English

java运行bash脚本,找不到命令

[英]java run bash script, command not found

I tried to use java to run some bash script and store the terminal output in a string. 我试图使用Java运行一些bash脚本并将终端输出存储在字符串中。 However, there are a lot of commands don't work in this way. 但是,有许多命令无法以这种方式工作。 It keeps showing command not found, but I can run those commands correctly in terminal, ex node --version, go --version. 它始终显示未找到的命令,但是我可以在终端中正确运行这些命令,例如node --version,go --version。 I guess is the path issue, but have no idea how to fix it. 我想这是路径问题,但不知道如何解决。

Another question, when I run "python --version", it shows "Python 2.7.10" but it is in getErrorStream. 另一个问题,当我运行“ python --version”时,它显示为“ Python 2.7.10”,但它在getErrorStream中。 Can anyone give me some hint? 谁能给我一些提示?

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);
    }
}

Reply @VishalKamat comment. 回复@VishalKamat评论。
when I tried using the output of "which node" as my path, which is "/usr/local/bin/node". 当我尝试使用“哪个节点”的输出作为我的路径时,即“ / usr / local / bin / node”。 It works!!! 有用!!!
But, does that mean I have to change the path when I need to get different application version info? 但是,这是否意味着我需要获取其他应用程序版本信息时必须更改路径? I thought I can easily get the info just like I do in terminal. 我以为我可以像在终端机中一样轻松地获取信息。

I try to print $PATH by java in this way 我尝试以这种方式通过java打印$ PATH

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

The error msg is : 错误消息为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM