Operating System - HP-UX
1753845 Members
7474 Online
108806 Solutions
New Discussion юеВ

Re: Script for capturing pid of particular process

 
SOLVED
Go to solution
Vincent Farrugia
Honored Contributor

Script for capturing pid of particular process

Hello,

I want to capture ONLY the process id of a particular process and store it in a variable.

Example, if the process id of the process "aaa" is 5643, the variable should store 5643.

How would you do this?
Tape Drives RULE!!!
8 REPLIES 8
Justo Exposito
Esteemed Contributor
Solution

Re: Script for capturing pid of particular process

Hi Vincent,

Try this:
PID=$( ps -ef |grep "aaa" | grep -v grep| sed 's/\ \{1,\}/#/g'| cut -d"#" -f3)
echo $PID

Regards,

Justo.
Help is a Beatiful word
Ceesjan van Hattum
Esteemed Contributor

Re: Script for capturing pid of particular process

Hi, try this:

PID=`ps -ef | grep $PROCNAME | grep -v grep | awk '{print $2}'`
echo $PID

Greetings,
Ceesjan
Nick Wickens
Respected Contributor

Re: Script for capturing pid of particular process

or this -

PID=$(ps -ef|grep thingtogrepfor | grep -v grep|cut -c10-14

So many ways to skin that cat (as we say in the UK).
Hats ? We don't need no stinkin' hats !!
V. V. Ravi Kumar_1
Respected Contributor

Re: Script for capturing pid of particular process

hi,
try this.

pid=`ps -ef|grep "process name"|awk '{print $2}'`

regds
Never Say No
Vincent Farrugia
Honored Contributor

Re: Script for capturing pid of particular process

Thank you.
Tape Drives RULE!!!
Bill Hassell
Honored Contributor

Re: Script for capturing pid of particular process

Oops. ps -ef | grep -v grep | grep is VERY unreliable. The problem is that grep doesn't know that you specifically want just the process name, and not the path or the arguments or even the user ID. Try this:

ps -ef | grep -v grep | grep sh

(to look for all the sh programs (but it finds ksh and csh and bash and users with the name cash and shenn, etc

Use this instead:

PIDVAR=$(UNIX95= ps -C MyProcessName | tail -1 | grep -v PID | awk '{print $1}')

where MyProcessName is the name of your selected process. This script will return the last match (in case there are two or more processes) and PIDVAR will be null if the process is not running. By using the XPG4 option -C, you are asking ps to do the searching for you and it will always match the basename of the process you are looking for.

In the above example, here is what you need:

UNIX95= ps -fC sh

and now you see only the sh (and the login shells -sh).


Bill Hassell, sysadmin
Wodisch_1
Honored Contributor

Re: Script for capturing pid of particular process

...and if you add '-o "" ' to Bill's example, you can save the "grep -v PID", as then there will be no header line...
Anand Hotchandani
New Member

Re: Script for capturing pid of particular process

Hi,

Var=`ps -ef | grep "aaa" | grep -v grep | awk '{print $2}'`

echo $var

Hope this will helps you.

Regards
Anand Hotchandani