Skip to content
shellhacks.dev
Linux

Find a Process by Name on Linux with pgrep

Find a process with pgrep. By default it matches only the name, limited to 15 characters, and -f matches the full command line, which -a then prints.

2 min read
Summarize in AI

You need the PID of a script that is running, and pgrep finds nothing for a name you can see in ps.

Shell
cp /bin/sleep /tmp/worker-with-a-long-name
/tmp/worker-with-a-long-name 300 &
sleep 0.3
echo "by name: $(pgrep worker-with-a-long-name | wc -l) match"
echo "full name cut to 15: $(pgrep worker-with-a- | wc -l) match"
echo "-f: $(pgrep -f worker-with-a-long-name | wc -l) match"
pgrep -a -f 'worker-with-a-long-name 300' | cut -d' ' -f2-
echo "exact: $(pgrep -x worker-with-a-l | wc -l) match"
kill $!; wait
Text
pgrep: pattern that searches for process name longer than 15 characters will result in zero matches
Try `pgrep -f' option to match against the complete command line.
by name: 0 match
full name cut to 15: 1 match
-f: 1 match
/tmp/worker-with-a-long-name 300
exact: 1 match

Without -f, pgrep compares the pattern, which is a regular expression, with the process name only, and the kernel stores that name cut to 15 characters, so a pattern longer than that matches nothing, and pgrep says so on standard error, as the first two lines of output show. -f matches against the whole command line, and -a prints that line next to the PID, as the pgrep manual describes. -x requires the whole name to match, using the shortened name, which the last line shows.

pgrep never matches itself, but -f matches any other process whose command line holds the pattern, including a shell running bash -c with the pattern in its text, so a script can find its own wrapper. Anchor the pattern with ^ or use -x, and check the list with -a before using it to kill anything. The exit status is 1 when nothing matched.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.