As a Linux power user, being able to quickly search and filter running processes is an invaluable skill. The pgrep command provides simple yet powerful options for hunting down processes based on name, user, and other attributes. In this comprehensive pgrep tutorial, you’ll learn how to leverage this tool through hands-on examples and expert tips.
Introduction to Managing Processes with pgrep
On a typical Linux system, there can be hundreds of processes running from critical system services to user applications. Having visibility into what processes are running and being able to search through them is crucial for administration, troubleshooting, and performance monitoring.
The ps and top commands provide a snapshot of currently running processes, but don’t allow filtering or searching process lists efficiently. This is where pgrep shines. Just as grep allows searching text, pgrep allows searching processes.
pgrep gives you the ability to:
- Find processes by full or partial name match
- Filter processes by user or other attributes
- Search oldest or newest processes first
- Get process counts rapidly
- Fetch process IDs into scripts for signaling etc
Mastering pgrep usage allows you to answer critical questions like:
- Is Process XYZ running already? How many instances?
- What’s the PID for my Java app I need to feed to
kill? - Which processes is User A running that are consuming high CPU?
- When did this rogue process first get started?
And many more. Let’s dive into examples of using pgrep for common process management tasks.
Finding Processes by Name
The most basic pgrep usage is searching for processes by name. For example, to find all bash processes:
pgrep bash
This prints any matching process IDs (PIDs):
4493
20134
You can search for any process name like sshd, httpd, firefox etc:
pgrep firefox
pgrep sshd
Partial Matches and Limitations
One detail about pgrep is that by default it will match any process name containing the search term anywhere in the name.
So for example, pgrep bash would also match processes named bashbug, mybashscript etc.
This behavior can be convenient in some cases, but also means pgrep can‘t precisely match exact process names without using regular expressions.
In many cases, the "contains" style search is sufficient. But for 100% accuracy, it‘s better to combine pgrep with additional filtering:
pgrep firefox | grep -F firefox
The -F flag does a fixed string match. We‘ll cover more examples of post-filtering pgrep output later on.
Searching by User
You can filter pgrep results to only show processes for a specific user via the -u option:
pgrep -u bob firefox
This will only return PIDs for Firefox processes owned by user "bob".
Searching by user is handy for seeing what processes a particular user may be running that are consuming resources or behaving unexpectedly.
Finding Process Count
To quickly get a count of matching processes, use the -c option:
pgrep -c sshd
This prints the number of sshd processes currently running:
3
The process count can give you a rapid health check, for example to monitor that exactly 1 sshd is running as expected.
Displaying Full Command Lines
When debugging issues with a particular process, it‘s often handy to see the full command line invocation used to start it.
pgrep can show this with the -f option:
pgrep -f firefox
Output:
4493 /usr/bin/firefox
20134 /usr/bin/firefox -P production
This allows you to differentiate parent/child processes or problem processes started a certain way.
Filtering Oldest and Newest Processes
By default pgrep will sort results with the newest process first. To see the oldest matches first, useful for finding long-running processes, use -o:
pgrep -o firefox
To filter specifically for the single oldest or newest match, you can pipe to head/tail:
pgrep -o firefox | head -n 1 # oldest
pgrep firefox | tail -n 1 # newest
Ignoring Case Sensitivity
pgrep matches process names case-sensitively by default. To make results case-insensitive, use -i:
pgrep -i FIREfox
This allows matching processes like FireFox or firefox.
Changing Output Delimiter
By default each pgrep result is delimited by a newline. To change the delimiter character, use -d:
pgrep -d, sshd
Output:
4234,20155,10532
Showing Process Names
To print the full process name along with the PID, use -l:
pgrep -l sshd
Result:
4234 sshd
20155 sshd
10532 sshd
Combining Options for Precision
The real power of pgrep comes from chaining multiple options together to hone in on processes precisely.
For example, to see full commands for a user‘s Firefox processes sorted oldest first:
pgrep -o -u bob -a firefox
Or count of case-insensitive matches:
pgrep -ci sshd
With just a few options, you can fine-tune pgrep to pull back exactly the process information you need.
Comparing pgrep to ps and grep
The ps and grep commands can also be used to search through processes in different ways compared to pgrep:
ps: Provides detailed info on every process. Good for inspecting overall system health.grep: Can searchpsoutput to filter processes reactively.pgrep: Specialized for proactively searching processes by criteria.
For one-off process inspection, ps and grep together can get the job done:
ps aux | grep ‘[f]irefox‘
But advantages of using pgrep include:
- Simple criteria-based searching for process names, users etc
- Fetch PIDs quickly without parsing
pstext output - Designed for process searching, vs general
greptext matching - Portable options like
-u,-o,-lthat work across Unix-like systems - Avoid needing superuser access to see full process lists
So in summary, for targeted process searching and filtering, pgrep makes life much easier!
Finding PIDs to Signal Processes
A very common use case for pgrep is to conveniently look up process IDs by name so they can be fed into process signaling tools like kill, pkill, top, strace etc.
For example, to send a TERM signal to firefox processes:
# Lookup PIDs
PIDS=$(pgrep firefox)
# Signal each PID
for PID in $PIDS
do
kill -TERM $PID
done
Or to investigate I/O usage with strace:
PID=$(pgrep -o firefox) # oldest PID
strace -p $PID
Looking up PIDs by name saves you from having to dig through ps output or maintain a PID lookup table.
Using pgrep in Scripts
In addition to the terminal, pgrep is very useful in shell scripts for looking up process info.
Some examples:
Check if process is running:
if pgrep -x sshd > /dev/null; then
echo "sshd is running"
else
echo "sshd stopped!"
fi
Restart process if too many instances:
PIDS=$(pgrep apache2)
if [ $(echo "$PIDS" | wc -l) -gt 3 ]; then
echo "Too many apache2 processes! Restarting..."
systemctl restart apache2
fi
Get process count across servers:
for server in web{1..5} app{1..3} db{1..2}; do
echo "$server: $(ssh $server pgrep -c postgres)"
done
Since pgrep matches by name, it‘s very useful for looking up info in scripts vs trying to parse ps output.
Piping to Other Commands
pgrep is designed to be combined with other standard Unix commands via piping:
pgrep sshd | wc -l # Count
pgrep apache2 | awk ‘{print $1}‘ > pids.txt # Extract PIDs
pgrep -f python | sort -k 1 # Sort by PID
pgrep firefox | head -2 # First two
Piping pgrep to tools like sort, head, wc, awk etc enables further processing on result sets.
When to Use pgrep vs killall
The killall command can also signal processes by name similarly to pgrep. However, there are some notable differences:
pgrepfinds matching PIDs,killalldirectly signals themkillallrequires exact name matches or regex- No search filtering options like
-uwithkillall killalldefaults to signal 15TERMvs info lookup withpgrep
In summary:
pgrepis best for searching/filtering processes to get PIDskillallis best for directly signaling exact name matches
So pgrep + kill gives you more flexibility than just killall alone.
Potential Issues and Limitations
While extremely useful, pgrep does have some limitations and areas to be aware of:
Partial name matching – The contains-style name search can lead to unwanted extra results if you‘re looking for an exact name. Use additional filtering like grep -F if required.
Access restrictions – pgrep will only show processes visible to the user executing it. Use sudo if needed.
Changing PIDs – Since PIDs can get reused, be careful storing PIDs for long periods or assuming permanence.
Process tree complexity – Child or threaded processes can appear separate from parents, depending on settings.
High process count – There can be hundreds of processes running on a system. Use filtering options wisely to narrow down results.
Root permissions – Avoid running pgrep as root for safety reasons. Use -u to check other users‘ processes.
Despite some things to look out for, pgrep remains an invaluable tool if used properly.
Tips and Best Practices
Here are some tips for getting the most out of pgrep:
- Learn basic regex to match names more flexibly if needed
- Double check matches to avoid acting on incorrect processes
- Combine with
grep,awk,sortetc for robust filtering - Store found PIDs temporarily if signaling processes across scripts
- Prefer
-ufor checking other user processes vs running pgrep as root - Read
man pgrepfor obscure options like-sfor selecting signals - Remember
-icase insensitivity and-vinverting matches
Following best practices like these will help avoid issues and use pgrep safely and effectively.
pgrep Commands Cheat Sheet
Here is a quick cheat sheet for reference of common pgrep commands:
| Command | Description |
|---|---|
pgrep bash |
Find processes named bash |
pgrep -u bob |
Find bob‘s processes |
pgrep -fl sshd |
Show full command line |
pgrep -cil httpd |
Count httpd processes case-insensitive |
pgrep -o vim |
Show oldest process first |
pgrep -d; nginx |
Set ‘;‘ delimiter for PIDs |
pgrep -lf chrome |
Show process names and PIDs |
pgrep Recipes
To help cement pgrep proficiency, here are some handy one-liner recipes for common use cases:
- Find zsh shell PIDs:
pgrep zsh - Show usernames for PIDs:
pgrep -l -u $(whoami) - Count your Python processes:
pgrep -cil python - Find oldest vim process:
pgrep -o vim | head -1 - Send HUP signal to apache2:
kill -HUP $(pgrep apache2) - Check for 3+ firefox processes:
test $(pgrep -c firefox) -gt 3
Learn these recipes and you‘ll have pgrep mastery in no time!
Conclusion
The pgrep command is an indispensable tool for any Linux administrator or developer. Its simple yet flexible matching and filtering options empower searching through running processes quickly and easily.
In this comprehensive guide, we covered real-world examples of using pgrep for process monitoring, signaling, troubleshooting, and more. Plus best practices and tips for avoiding issues and using pgrep like a pro.
With a bit of practice, pgrep will become second nature for common tasks like:
- Finding a process PID by name
- Checking if a process is already running
- Getting process counts
- Filtering background jobs by user
- Fetching PIDs for shell scripts
I encourage you to open up a terminal window and try out some of the pgrep commands shown to see just how useful it can be. Mastering this tool will level up your Linux process management skills.
So in summary – learning pgrep is time well spent for anyone working on Linux! It will pay dividends for years to come in terms of making you more productive and empowered on the command line.



