How to get only process ID in specify process name in linux?

RegexLinuxShellRedhat

Regex Problem Overview


How to get only the process ID for a specified process name in linux?

ps -ef|grep java    
test 31372 31265  0 13:41 pts/1    00:00:00 grep java

Based on the process id I will write some logic. So how do I get only the process id for a specific process name.

Sample program:

PIDS= ps -ef|grep java
if [ -z "$PIDS" ]; then
echo "nothing"
else
mail test@domain.com
fi

Regex Solutions


Solution 1 - Regex

You can pipe your output to awk to print just the PID. For example:

> ps -ef | grep nginx | awk '{print $2}' > 9439

Solution 2 - Regex

You can use:

ps -ef | grep '[j]ava'

Or if pgrep is available then better to use:

pgrep -f java

Solution 3 - Regex

Use this: ps -C <name> -o pid=

Solution 4 - Regex

This command ignore grep process, and just return PID:

ps -ef | grep -v grep | grep java | awk '{print $2}'

Solution 5 - Regex

why not just pidof ?

pidof <process_name>

it will return a list of pids matching the process name

https://linux.die.net/man/8/pidof

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionopenquestionView Question on Stackoverflow
Solution 1 - RegexJose VarezView Answer on Stackoverflow
Solution 2 - RegexanubhavaView Answer on Stackoverflow
Solution 3 - RegexventsyvView Answer on Stackoverflow
Solution 4 - RegexNabi K.A.Z.View Answer on Stackoverflow
Solution 5 - RegexPorungaView Answer on Stackoverflow