简体   繁体   中英

Unable to get output from shell script command in java

I'm running a shell script command in java program using ProcessBuilder, here is my code :

String lastLine = "";

ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", "echo $(ps -eo pid,args | grep -v grep | grep -v \"$$"\ | grep feature_service.sh | awk '{print $1}')");

BufferedReader reader =
                    new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;
            while ((line = reader.readLine()) != null) {
                lastLine = line;
            }

Output from this : empty string ("")

But if i run the same command on terminal it is working fine (pid of process).

Please help me.

Following simplified Shell command is working.

ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", 
    "-c", 
    "ps -eo pid,args|grep [f]eature_service.sh|awk '{print $1}'|tr '\\n' ' '");
  • ps -eo pid,args - list the process ID and the arguments
  • grep [f]eature_service.sh - grep for the string feature_service.sh in the arguments, the [f] avoid the multiple usage of grep in the chain
  • awk '{print $1}' - print the first column of the output, using default whitespace characters as delimiter
  • tr '\\n' ' ' - replace all newline cracaters in the output by a space character

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM