1

Good day all,

I am trying to write a bash script to show all processes of java, however i would like it to display in the below manner.

 ps -p $PID -o pid,vsz=MEMORY -o user,group=GROUP -o comm,args=ARGS

The problem with the above is that it only show one particular PID.

So I want to ps aux|grep j\[a\]va get the PID of each and then run each PID in the above command.

RESULT:

 root@reinhardt-VirtualBox:/home/reinhardt# ps -p 1959 -o pid,vsz=MEMORY -o user,group=GROUP -o comm,args=ARGS
  PID MEMORY USER     GROUP    COMMAND         ARGS
 1959  13648 root     root     grep            grep --color=auto java

I would guess some sort of loop will be made like for loop?

0

Not in a place where I can test this, but this should work. read is a standard part of shell scripting, it places something from stdin (which can be a stream, or a device such as /dev/tty) into a variable. Then you just do a while loop

ps auwwx | gawk '/[j]ava/{print $1}' | while read PID
do
    ps -p $PID -o pid,vsz=MEMORY -o user,group=GROUP -o comm,args=ARGS
done

Or more simply, if your UNIX has pgrep:

pgrep java | while read PID
do
    ps -p $PID -o pid,vsz=MEMORY -o user,group=GROUP -o comm,args=ARGS
done

Sometimes you can use xargs in cases like these. Remember that by default, xargs puts a group of arguments at the end of the command. So you need to feed it one at a time (with -n1) and place the PID where you want, with -i:

pgrep java | xargs -n1 -i{} ps -p {} -o pid,vsz=MEMORY -o user,group=GROUP -o comm,args=ARGS

(again, apologies if I get the -i syntax wrong, I can't test now. Check manpage if this blows up)

| improve this answer | |
  • Awesome, tried the 1st piece of code, 2 problems, it said gawk is not known. I then took out the g and then the script ran through the loop, however i am not sure if the PID is inserted into the $PID. I get "error: process ID list syntax error" – Reinhardt Ratkas van Rooyen Oct 28 '14 at 15:33
  • Oh and the last one is working perfectly! – Reinhardt Ratkas van Rooyen Oct 28 '14 at 15:36
  • @ReinhardtRatkasvanRooyen is this on a Mac? My assumption was Linux, therefore gawk. – Rich Homolka Oct 28 '14 at 16:28
  • This is linux, Ubuntu 13 – Reinhardt Ratkas van Rooyen Oct 29 '14 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.