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/[
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.\"'";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With