3

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.

Rajib Biswas
  • 772
  • 10
  • 27

1 Answers1

3

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}'"

Bernhard
  • 8,583
  • 4
  • 41
  • 42