Site icon DesignLinux

Pgrep Command in Linux

Pgrep Command in Linux

The pgrep is a command-line utility used to find the process IDs of a running application. It’s inlcuded in procps package and pre-installed on most of the Linux distributions. The process name can be full or partial, which running by a user or other attributes. This article we will discuss the basics of the Linux pgrep command.

Use pgrep Command

Following is the basic syntax of the pgrep command:

pgrep [OPTIONS] <PATTERN>

Once you run the pgrep command without any options, it will show the PIDs of all running programs which matches with given names.

For example, to get the PID of the Nginx server, you would run:

pgrep nginx

If the processes found with the matching name “nginx”, it show the PIDs of the processes. Otherwise it will not show any output.

23101
23104

If any one running process matches with the given name it will returns 0, otherwise the exit code is 1. It can be useful while writing shell scripts.

If you want to send signals to the matched processes use pkill . This uses same options and pattern matching.

By default the pgrep command will print the each PID on a newline. You can change the delimiter to separate using the -d option.

For example, if you want to use a pipe sign as a delimiter, enter:

pgrep nginx -d'|'
23101|23104

The -l option tells pgrep to show the process name along with its ID:

pgrep nginx -l
23101 nginx
23104 nginx

You also can use the regular expression with pgrep command to do search operation and it will list all the processes that having the name “nginx”.

If you want to match only the processes which names are exactly as the search pattern, you would use:

pgrep '^nginx$' -l
23101 nginx
23104 nginx

The pgrep matches only against the process name, you can use the -f option to matches against full argument lists.

pgrep nginx -f

To get the list of processes of a specific user use -u option with pgrep command:

pgrep -u root

You also can specify the multiple users names with comma separated list:

pgrep -u root,tecnstuff

Conclusion

The pgrep command is used to get the PIDs of a running program. To know more about pgrep command, take a look at pgrep man page.

If you have any questions or feedback, feel free to leave a comment.

Exit mobile version