Saturday, March 10, 2007

Filtering the unix ps command

Suppose you want to list the active processes on your system. You would use the "ps" command:

$ ps


PID PPID SIZE ENV DS Command
0254 0008 02db
0530 0008 0004
0535 8e7e 06fe 0000 0545 (SH) -L -0 C:/UNIX/BIN/SH.EXE -R 0
0c34 10ae 0010
0c45 26d1 0010
0c56 FREE 001e 480 bytes
0c75 0535 0438 0c34 0c75 (mouse.co)
10ae 0535 0055 0c34 10ae (vi.exe) \unix\bin\vi.exe
1104 10ae 15cc 0000 2111 (/unix/bi) -c ps
26d1 1104 02a5 0c45 285d (ps.exe) \unix\bin\ps.exe


$

Now, suppose you are only interested in the process information
for "vi". You could do the following:


$ ps | grep vi
10ae 0535 0056 0c34 10ae (vi.exe) \unix\bin\vi.exe
1105 10ae 15cd 0000 2112 (/unix/bi) -c ps | grep vi


$

The problem is that you also get the entry for the "grep" process itself.


There is a simple, elegant solution:

$ ps | grep [v]i
10ae 0535 0056 0c34 10ae (vi.exe) \unix\bin\vi.exe

$

In regular expressions, brackets contain either-or options. So "[sz]ys" would match "sys" or "zys". If only one character is in brackets, as in "[v]i", then the regular expression simplifies to "vi" upon execution.

Thus, in our case, "grep" is simply looking for "vi", but the "ps" entry
for the "grep" contains the original "[v]i", so we prevent a match.

0 comments: