leah blogs

July 2013

25jul2013 · Summer of Scripts: px

A classic “failure” in shell scripting is to grep the output of ps, which easily generates an erroneous additional result:

% ps ax |grep emacs
 2941 ?        SN    48:31 emacs
21771 pts/27   SN+    0:00 grep emacs

Some people try to fix that this way:

% ps ax |grep emacs |grep -v grep
 2941 ?        SN    48:32 emacs

But that is lame of course, because just making the argument not match itself literally is enough:

% ps ax |grep [e]macs
 2941 ?        SN    48:32 emacs

Clearly, there has to be a better way. I simply use this:

# px -- verbose pgrep
px() {
  ps uwwp ${$(pgrep -d, "${(j:|:)@}"):?no matches}
}

Since it uses pgrep, it searchs inside the program string only:

% px emacs
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
chris     2941  0.0  0.9 162184 76056 ?        SN   Jun08  48:33 emacs

% px swap
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root        35  0.0  0.0      0     0 ?        S    Jun08   9:22 [kswapd0]

NP: Die Schnitter—Orange

Copyright © 2004–2022