The difference between pidof and pgrep

process

When I use either of these commands with an argument as the name of a process, both of them return the exact same number. Are they the same commands? Are they two different commands that do the same thing? Is one of them an alias to the other?

pidof firefox
pgrep firefox

Best Answer

The programs pgrep and pidof are not quite the same thing, but they are very similar. For example:

$ pidof 'firefox'
5696
$ pgrep '[i]ref'
5696
$ pidof '[i]ref'
$ printf '%s\n' "$?"
1

As you can see, pidof failed to find a match for [i]ref. This is because pidof program returns a list of all process IDs associated with a program called program. On the other hand, pgrep re returns a list of all process IDs associated with a program whose name matches the regular expression re.

In their most basic forms, the equivalence is actually:

$ pidof 'program'
$ pgrep '^program$'

As yet another concrete example, consider:

$ ps ax | grep '[w]atch'
   12 ?        S      0:04 [watchdog/0]
   15 ?        S      0:04 [watchdog/1]
   33 ?        S<     0:00 [watchdogd]
18451 pts/5    S+     0:02 watch -n600 tail log-file
$ pgrep watch
12
15
33
18451
$ pidof watch
18451