Question

I need to extract PID, UID and command fields from 'ps' and I have tried it like this:

ps -L u n | cut -f 1,2,13

For some reason, this behaves as there is no cut command whatsoever. It just returns normal ps output. Then, I tried

ps -L u n | tr -s " " | cut -d " " -f 1,2,13 and this returns total nonsense. Then, I tried playing with it and with this:

ps -L u n | tr -s " " | cut -d " " -f 2,3,14

and this somehow returns what I need (almost, and I don't understand why that almost works), except that it cuts out the command field in the middle of it. How can I get what I need?

Was it helpful?

Solution

ps is printing out space separators, but cut without -d uses the tab character. The tr -s squeezes the spaces together to get more of the separation that you want, but remember that there is the initial set of spaces (squeezed to one) hence why you need to add 1 to each field. Also, there are spaces in the commands for each word. This should work:

ps -L u n | tr -s " " | cut -d " " -f 2,3,14-

OTHER TIPS

Is there any particular reason for using cut?

I guess this will do what you want:

ps -eopid,uid,cmd

You can use awk to clean up your command, like so:

ps -L u n | awk '{ print $1,$2,$13 }'

The question is what to do once you have a list. I find cut kludgy, so instead of cut I pass the list to a while read loop. "While read" recognizes non-blank values on a line, so in this example, "a" is the first value, "b" is the second and "c" is the rest of the line. I am only interested in the first 2 values, process owner and process ID; and I basically abuse the case statement rather than use an "if". (Even though grep filtered, I don't want to kill processes where the owner name might be embedded elsewhere in the line)

ps -ef | grep owner | grep -v grep | while read a b c; 
do 
 case $a in 
  "owner")
     kill -9 $b  
   ;; 
 esac; 
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top