2016-05-29 120 views
0

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

另一个问题,当我运行“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); 
    } 
} 
+0

你可以尝试给予命令,而不是仅仅名称完整路径。 “哪个节点”会给你路径。尝试在你的java代码中使用它。另外值得从java中回显$ PATH以查看与终端的区别 –

+0

关于“getErrorStream”:如您所知,程序可能使用两个流来打印信息。程序本身决定使用哪一个。虽然有相当一些官方指导打印什么,但这通常不能准确处理。在你的情况下,python显然是这样做的... – EagleRainbow

+0

@VishalKamat我在下面回复它。感谢您的好评和有用的评论! – user3390980

回答

0

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

我尝试打印在Java $ PATH这样

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

错误味精:

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

该命令是“echo $ PATH”来打印该值 –