Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot execute a Linux command from Java

Tags:

java

linux

bash

I have a Linux command that I cannot execute from Java:

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

It works fine in command line but when I use the following code:

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

it says that

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

Any idea? Is it possible that these IF bash operators cannot be called from Java...?

Thanks!

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

vikhor@adnlt653-vm1:~> which '['
[ is a shell builtin
[ is /usr/bin/[
[ is /bin/[
like image 669
Viktor Avatar asked Jan 23 '26 00:01

Viktor


1 Answers

The [ command is a shell built-in. The which command shows that it's also an executable file. It is this executable file that gets executed when you pass the command line to exec(). So then the whole command line is passed to the [ command. However, the && operator is a shell operator. The [ executable doesn't like it.

So you need to run the bash executable and pass the command as an argument:

String command = "bash -c '[ ! -d \"/tmp/flow\" ] && echo \"The directory DOES NOT exist.\"'";
like image 162
DodgyCodeException Avatar answered Jan 24 '26 22:01

DodgyCodeException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!