How to get PID of process by specifying process name and store it in a variable to use further?

UnixProcessPid

Unix Problem Overview


By using "ucbps" command i am able to get all PIDs

 $ ucbps
  
   Userid     PID     CPU %  Mem %  FD Used   Server                  Port
   =========================================================================
      
   512        5783    2.50   16.30  350       managed1_adrrtwls02     61001
   512        8896    2.70   21.10  393       admin_adrrtwls02        61000
   512        9053    2.70   17.10  351       managed2_adrrtwls02     61002

I want to do it like this, but don't know how to do

  1. variable=get pid of process by processname.
  2. Then use this command kill -9 variable.

Unix Solutions


Solution 1 - Unix

If you want to kill -9 based on a string (you might want to try kill first) you can do something like this:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}'

This will show you what you're about to kill (very, very important) and just pipe it to sh when the time comes to execute:

ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}' | sh

Solution 2 - Unix

pids=$(pgrep <name>)

will get you the pids of all processes with the given name. To kill them all, use

kill -9 $pids

To refrain from using a variable and directly kill all processes with a given name issue

pkill -9 <name>

Solution 3 - Unix

On a single line...

pgrep -f process_name | xargs kill -9

Solution 4 - Unix

Another possibility would be to use pidof it usually comes with most distributions. It will return you the PID of a given process by using it's name.

pidof process_name

This way you could store that information in a variable and execute kill -9 on it.

#!/bin/bash
pid=`pidof process_name`
kill -9 $pid

Solution 5 - Unix

use grep [n]ame to remove that grep -v name this is first... Sec using xargs in the way how it is up there is wrong to rnu whatever it is piped you have to use -i ( interactive mode) otherwise you may have issues with the command.

ps axf | grep | grep -v grep | awk '{print "kill -9 " $1}' ? ps aux |grep [n]ame | awk '{print "kill -9 " $2}' ? isnt that better ?

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
QuestionNidhi View Question on Stackoverflow
Solution 1 - UnixBenView Answer on Stackoverflow
Solution 2 - UnixXZSView Answer on Stackoverflow
Solution 3 - UnixStephenView Answer on Stackoverflow
Solution 4 - UnixflazzariniView Answer on Stackoverflow
Solution 5 - UnixPawel KView Answer on Stackoverflow