cd ../notes

TIL ·

Stop grep matching itself without grep -v grep

ps aux | grep nginx always lists the grep nginx process too, which is why | grep -v grep is so common. Wrap one character of the pattern in brackets instead:

bash
ps aux | grep '[n]ginx'

The regex [n]ginx still matches nginx, but grep’s own command line now contains the literal text [n]ginx, which the regex doesn’t match. Keep the quotes: unquoted, the shell treats [n]ginx as a glob, and if a file called nginx exists in the current directory, grep receives nginx and matches itself again.

Usually a dedicated tool is simpler:

bash
pgrep -a nginx            # PID + command line; never matches itself
pgrep -af 'nginx: worker' # match the full command line, not just the name
pidof nginx               # exact program name, PIDs only
ps -C nginx -o pid,args   # ps output columns, filtered by name

pgrep matches the process name (truncated to 15 characters) unless you pass -f. With -f, and with the grep trick, any process whose command line contains the pattern matches too — a wrapping bash -c '...' or ssh host '...' that mentions nginx will show up alongside the real process.