System and processes
The pgrep command
Searches processes by name or attributes and prints their PIDs, without the noise of ps aux | grep. Its output is a list of PIDs ready to use in scripts.
Most useful options
-lAlso shows the process name next to the PID.-aShows the full command line instead of the name.-u <usuario>Only processes of that user.-fMatches the pattern against the full command line, not only the name.-xExact match of the whole process name.-n / -o-n picks the newest process and -o the oldest.-cCounts the matching processes instead of showing their PIDs, handy for quick checks.-P <ppid>Only the children of the given parent process.Copy-ready examples
$ pgrep nginxPIDs of every process named nginx: the master and the workers.Example output
912 913 914
$ pgrep -a -u miguel nodenode processes owned by miguel, with their command line.Example output
4821 node servidor.js
$ pgrep -f 'python3.*backup'Searches the full command line, useful when the name is generic like python3.$ pgrep -c sshdHow many sshd processes are running: one per session plus the main one.Example output
3
You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| No error message | No process matches: pgrep exits with code 1 and prints nothing, so it is not a syntax error. | Check the name with pgrep -l or ps -e; in a script, use if pgrep ... to decide. |
| pgrep: no matching criteria specified | It was called without any pattern, for example pgrep with no name or only options. | Add the name or pattern after the options. |
| bash: pgrep: command not found | pgrep is part of procps, which is missing from Git Bash and some minimal images. | Install it with sudo apt install procps, or use ps aux | grep if you cannot install it. |
Typical mistakes
- Without -x, node also matches nodemon; on Linux the name is cut to 15 characters.
Differences from similar commands
FAQ
How do I know whether a script is already running?
Use if pgrep -f miscript.sh > /dev/null; then echo 'already running'; fi: pgrep returns 0 when it finds something.
What if several processes match and I want only one?
Use -n (the newest) or -o (the oldest) to keep just one.
Does pgrep match itself?
No: pgrep excludes its own process, so you do not need to filter it out.
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course