Más elegante "ps aux / grep-v grep"


Cuando compruebo la lista de procesos y 'grep' aquellos que son interesantes para mí, el grep en sí también se incluye en los resultados. Por ejemplo, para listar terminales:

$ ps aux  | grep terminal
user  2064  0.0  0.6 181452 26460 ?        Sl   Feb13   5:41 gnome-terminal --working-directory=..
user  2979  0.0  0.0   4192   796 pts/3    S+   11:07   0:00 grep --color=auto terminal

Normalmente uso ps aux | grep something | grep -v grep para deshacerme de la última entrada... pero no es elegante :)

¿Tienes un truco más elegante para resolver este problema (aparte de envolver todo el comando en un script separado, que tampoco está mal)

 157
Author: Jakub M., 2012-02-21

8 answers

La técnica habitual es la siguiente:

ps aux | egrep '[t]erminal'

Esto coincidirá con las líneas que contienen terminal, que egrep '[t]erminal' no! También funciona en muchos sabores de Unix.

 258
Author: Johnsyweb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-08 00:53:09

Use pgrep. Es más confiable.

 50
Author: DarkDust,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-12 14:02:18

Esta respuesta se basa en un anterior pgrep respuesta . También se basa en otra respuesta combinando el uso de ps con pgrep. Estos son algunos ejemplos de entrenamiento pertinentes:

$ pgrep -lf sshd
1902 sshd

$ pgrep -f sshd
1902

$ ps up $(pgrep -f sshd)
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root      1902  0.0  0.1  82560  3580 ?        Ss   Oct20   0:00 /usr/sbin/sshd -D

$ ps up $(pgrep -f sshddd)
error: list of process IDs must follow p
[stderr output truncated]

$ ps up $(pgrep -f sshddd) 2>&-
[no output]

Lo anterior se puede usar como una función :

$ psgrep() { ps up $(pgrep -f $@) 2>&-; }

$ psgrep sshd
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root      1902  0.0  0.1  82560  3580 ?        Ss   Oct20   0:00 /usr/sbin/sshd -D

Compare con usar ps con grep. La fila útil del encabezado no se imprime:

$  ps aux | grep [s]shd
root      1902  0.0  0.1  82560  3580 ?        Ss   Oct20   0:00 /usr/sbin/sshd -D
 23
Author: A-B-B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-20 15:09:20

Puede filtrar en el comando ps, por ejemplo,

ps u -C gnome-terminal

(o buscar a través de / proc con find etc.)

 7
Author: Andreas Frische,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 15:25:59

Una alternativa más :

ps -fC terminal

Aquí las opciones:

 -f        does full-format listing. This option can be combined
           with many other UNIX-style options to add additional
           columns. It also causes the command arguments to be
           printed. When used with -L, the NLWP (number of
           threads) and LWP (thread ID) columns will be added. See
           the c option, the format keyword args, and the format
           keyword comm.

 -C cmdlist     Select by command name.
                This selects the processes whose executable name is
                given in cmdlist.
 3
Author: TaXXoR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-30 07:57:03

El uso de corchetes para rodear un carácter en el patrón de búsqueda excluye el proceso grep ya que no contiene la expresión regular coincidente.

$ ps ax | grep 'syslogd'
   16   ??  Ss     0:09.43 /usr/sbin/syslogd
18108 s001  S+     0:00.00 grep syslogd

$ ps ax | grep '[s]yslogd'
   16   ??  Ss     0:09.43 /usr/sbin/syslogd

$ ps ax | grep '[s]yslogd|grep'
   16   ??  Ss     0:09.43 /usr/sbin/syslogd
18144 s001  S+     0:00.00 grep [s]yslogd|grep
 3
Author: auntchilada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-13 18:33:16

Descargo de responsabilidad: Soy el autor de esta herramienta, pero...

Usaría px :

~ $ px atom
  PID COMMAND          USERNAME   CPU RAM COMMANDLINE
14321 crashpad_handler walles   0.01s  0% /Users/walles/Downloads/Atom.app/Contents/Frameworks/Electron Framework.framework/Resources/crashpad_handler --database=
16575 crashpad_handler walles   0.01s  0% /Users/walles/Downloads/Atom.app/Contents/Frameworks/Electron Framework.framework/Resources/crashpad_handler --database=
16573 Atom Helper      walles    0.5s  0% /Users/walles/Downloads/Atom.app/Contents/Frameworks/Atom Helper.app/Contents/MacOS/Atom Helper --type=gpu-process --cha
16569 Atom             walles   2.84s  1% /Users/walles/Downloads/Atom.app/Contents/MacOS/Atom --executed-from=/Users/walles/src/goworkspace/src/github.com/github
16591 Atom Helper      walles   7.96s  2% /Users/walles/Downloads/Atom.app/Contents/Frameworks/Atom Helper.app/Contents/MacOS/Atom Helper --type=renderer --no-san

Excepto para encontrar procesos con una interfaz de línea de comandos sensible, también hace muchas otras cosas útiles, más detalles en la página del proyecto.

Funciona en Linux y OS X, se instala fácilmente:

curl -Ls https://github.com/walles/px/raw/python/install.sh | bash
 2
Author: Johan Walles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-10 09:20:20

Otra opción es editar su .bash_profile (u otro archivo en el que mantenga alias bash) para crear una función que greps 'grep' de los resultados.

function mygrep {
grep -v grep | grep --color=auto $1
}

alias grep='mygrep'

El grep -v grep tiene que ser el primero, de lo contrario su --color=auto no funcionará por alguna razón.

Esto funciona si estás usando bash; si estás usando un shell diferente YMMV.

 -2
Author: FlyingCodeMonkey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-22 17:22:33