Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Runtime.getRuntime().exec() getting error: /bin/bash: No such file or directory [duplicate]

Tags:

java

bash

macos

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.

like image 960
Rajib Biswas Avatar asked Jun 30 '26 22:06

Rajib Biswas


1 Answers

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

like image 110
Bernhard Avatar answered Jul 02 '26 12:07

Bernhard



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!