88

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.example
fi
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
openquestion
  • 933
  • 1
  • 7
  • 6

5 Answers5

106

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

ps -ef | grep nginx | awk '{print $2}'
9439
Jose Varez
  • 2,019
  • 1
  • 12
  • 9
  • Works well, hoverver if you use the output as a variable, a | tr -d '\n' must be added at the end of the command. – рüффп Jul 20 '20 at 09:46
  • It is a program that can be used to select particular records in a file and perform operations upon them. It is so extensive that you can even write some programs with it. [AWK Documentation](https://www.gnu.org/software/gawk/manual/gawk.html) – Gilberto Treviño Jul 01 '21 at 12:45
104

You can use:

ps -ef | grep '[j]ava'

Or if pgrep is available then better to use:

pgrep -f java
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Great answer pgrep -f java . It can be used to get PID only. – DollyShukla Feb 24 '21 at 10:02
  • 1
    Your first answer doesn't return only the pid, it returns all informations (on Ubuntu). BTW: Could you explain, what the brackets do? II couldn't find a doc for it. – dur Oct 15 '21 at 10:55
  • Square brackets are used to exclude grep process from ps output – anubhava Oct 15 '21 at 11:07
76

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

ventsyv
  • 3,316
  • 3
  • 27
  • 49
  • 16
    Why is this voted down? Not only does it seem to work, but does so using the desired command ps, and no pipe filters. In my case, I couldn't use pipes (reasons..) so this was a lifesaver. You could spend a whole day reading the man page for PS... thanks @ventsyv – Scott Prive Jul 29 '16 at 21:57
  • 2
    Maybe because it's not extremely portable, but then again the other solutions aren't either, and the original question was tagged with Redhat Linux. Just happened to see a commit by one of my engineers who needed to have a portable way to detect a specific java process on OSX, RHEL Linux and AIX, and this is what they came up with: `ps -A -o pid,args | grep \[j]ava`. – ikaerom Jun 05 '17 at 10:51
25

This command ignore grep process, and just return PID:

ps -ef | grep -v grep | grep java | awk '{print $2}'
Nabi K.A.Z.
  • 9,887
  • 6
  • 59
  • 81
21

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

NIEL Alexandre
  • 527
  • 4
  • 8