Is there a way to select by several conditions in `ps`?

ps is annoying that way. Fortunately, there is pgrep, which has similar selection options, but requires them all to match and then outputs the matching pids. By default it outputs one per line, but it can be asked to use a different delimiter so that it will work with ps:

ps -f -p"$(pgrep -d, -u $USER -P 1)"

Unfortunately ps can only deselect, there doesn't appear to be either an and operator or the ability to add refinements.

You can enlist the help of pgrep to get a list of PIDs and feed that to ps however. For example:

$ ps -f $(pgrep -P 1 -u saml)
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
saml      1986     1  0 Jul25 ?        SLl    0:00 /usr/bin/gnome-keyring-daemon --daemonize --login
saml      2003     1  0 Jul25 ?        S      0:00 dbus-launch --sh-syntax --exit-with-session
saml      2004     1  0 Jul25 ?        Ss     0:23 /bin/dbus-daemon --fork --print-pid 5 --print-address 7 --session
saml      2147     1  0 Jul25 ?        S      0:04 /usr/libexec/gconfd-2
saml      2156     1  0 Jul25 ?        Ssl    0:09 /usr/libexec/gnome-settings-daemon
saml      2162     1  0 Jul25 ?        S      0:00 /usr/libexec/gvfsd
saml      2178     1  0 Jul25 ?        Ssl    0:01 /usr/bin/pulseaudio --start --log-target=syslog
saml      2180     1  0 Jul25 ?        Ssl    0:04 /usr/libexec//gvfs-fuse-daemon /home/saml/.gvfs
saml      2191     1  0 Jul25 ?        S      0:12 syndaemon -i 0.5 -k
saml      2193     1  0 Jul25 ?        S      0:00 /usr/libexec/gvfs-gdu-volume-monitor

ps does not have very flexible filters. Make it display more than what you need, specify the format explicitly, and filter the output. Awk will often work well for this task.

ps -o pid= -o ppid= -o user= -o comm= -o args= |
awk -v uid="$(id -un myuser)" '$2 == 1 && $3 == uid'

The equal signs after the column names suppress the header line. If you want to see the header lines, make the filter print out the first line unchanged:

ps -o pid -o ppid -o user -o comm -o args |
awk -v uid="$(id -un myuser)" 'NR == 1 || ($2 == 1 && $3 == uid)'

If you want to do some automated processing, you'll need to strip the data down to the PIDs only.

ps -o pid= -o ppid= -o user= |
awk -v uid="$(id -un myuser)" '$2 == 1 && $3 == uid {print $1}'

Tags:

Linux

Ps