10

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
15

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
1

Fox has mentioned that pgrep searches using regular expressions, while pidof does not.

But pgrep also has a lot more options available:

  • With -u "$UID" you can match only processes belonging to the current user.
  • With --parent you can find the child processes of a given process.
  • You can select the --oldest or --newest of the matching processes.
  • ...and various others listed on the man page...

Let's find out which package each process belongs to (on apt systems):

$ dpkg -S "$(which pidof)"
sysvinit-utils: /bin/pidof

$ dpkg -S "$(which pgrep)"
procps: /usr/bin/pgrep

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.