0

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.

2
  • Does this compile? You've got two unescaped quotes inside a string, in "$$" (instead of \"$$\"). Commented Oct 21, 2016 at 7:07
  • i'm using this \"$$\" only in my program. thnx i will change here also. Commented Oct 21, 2016 at 7:16

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

command is working on terminal, but getting null (from bufferedReader) if running through java program.
@vinni I believe you run it differently. If your run /bin/bash -c echo $(...) in the terminal it returns nothing.
thnx or help, I'm using pgrep -f feature_service.sh and its working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.