I am trying to execute following from java code:
String[] cmd = { "/bin/bash", "netstat -nr | grep '^0.0.0.0' | awk '{print $2}'" };
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader inputError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = input.readLine()) != null) {
logger.info(line);
}
String lineError = null;
while ((lineError = inputError.readLine()) != null) {
logger.info(lineError);
}
On executing this, I am not getting any output from input stream. But in the error stream, I see following error:
/bin/bash: netstat -nr | grep '^0.0.0.0' | awk '{print $2}': No such file or directory
I have verified that /bin/bash is present and if I put the following content in a sh file and execute the same, I get proper output:
#!/bin/bash
netstat -nr | grep '^0.0.0.0' | awk '{print $2}'
I have looked into lot of similar issues in stackoverflow, but none of the solutions worked for me.
You need to provide the command that you want to execute as an argument to the -c option of /bin/bash
Such that the command you run through exec reads like: /bin/bash -c "netstat -nr | grep '^0.0.0.0' | awk '{print $2}'"
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