无法从Java

时间:2018-02-06 10:44:30

标签: java linux bash

我有一个Linux命令,我无法从Java执行:

[ ! -d "/tmp/flow" ] && echo "The directory DOES NOT exist."

它在命令行中工作正常,但是当我使用以下代码时:

    String command = "[ ! -d \"/tmp/flow\" ] && echo \"The directory DOES NOT exist.\"";
    Process proc = Runtime.getRuntime().exec(command);
    Boolean successful = proc.waitFor()==0 && proc.exitValue()==0;
    System.out.println("successful:"+successful);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    String line = null;
    System.out.println("************** input");
    while ((line = stdInput.readLine()) != null) {
        System.out.println(line);
    }
    System.out.println("************** error");
    while ((line = stdError.readLine()) != null) {
        System.out.println(line);
    }

它说

successful:false
************** input
************** error
[: missing ']'

有什么想法吗?是否有可能无法从Java调用这些IF bash运算符??

谢谢!

**************** UDATE ****************

vikhor@adnlt653-vm1:~> which '['
[ is a shell builtin
[ is /usr/bin/[
[ is /bin/[

1 个答案:

答案 0 :(得分:1)

[命令是内置的shell。 which命令显示它也是可执行文件。将命令行传递给exec()时,会执行此可执行文件。然后将整个命令行传递给[命令。但是,&&运算符是shell运算符。 [可执行文件不喜欢它。

因此,您需要运行bash可执行文件并将命令作为参数传递:

String command = "bash -c '[ ! -d \"/tmp/flow\" ] && echo \"The directory DOES NOT exist.\"'";