brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pgrep -af finds a process by its full command line

Linux
~/tips/tip-pgrep-af-full-command-line

pgrep -af 'sleep 301'

Lists the process IDs and full command lines of every process whose command line matches.

I like pgrep better than ps aux | grep, mostly because the output is just the matching processes. The catch is that it only looks at the process name unless you ask for more.

pgrep -af 'sleep 301'

The manual says the pattern is normally matched only against the process name. With -f it is matched against the full command line, so you can tell two sleep processes (or two python scripts) apart by their arguments. -a prints the full command line next to the process ID, which saves a second lookup.

With two background jobs, sleep 300 and sleep 301, procps-ng 4.0.4 printed this for pgrep -a sleep:

32520 sleep 300
32521 sleep 301

Adding -f 'sleep 301' narrowed it to the second one. Plain pgrep sleep prints only the two numbers. The other options I’d keep in mind:

  • -c prints a count of matching processes instead of the list.
  • -x only matches names (or command lines, with -f) that equal the pattern exactly.
  • -l lists the process name next to the ID, which is shorter than -a.

One caveat: the name that pgrep matches is limited to the 15 characters that appear in /proc/pid/stat, according to the manual. A long program name can match on its first 15 characters only, and -f is the way around that.

Further reading: pgrep(1) manual

More Linux tips notify-send -r "$id" "Backup" "Done" smbstatus -L msmtp --serverinfo --tls --tls-certcheck=off --host=smtp.example.com --port=587 smbclient //server/share -U user -Tc backup.tar "*" xz -T0 -k big.log All Linux tips (283) All topics

Link