Last updated on May 5th, 2016 at 01:06 am

Get pid of a process using shell script, Sometimes we come across situations where we need to find some process and read or retrieve it line by line using shell script in linux. Once it is retrieved we can use awk command to print the process id.

Here is a simple way to do that using WHILE..DO.

top -b -n 1 |grep java|while read -r line ; do
echo "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+";
echo "Processing Each line Now ->  $line"
echo "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+";
# Main Program Goes Here
done

I am using top command to find the java process and then read each line. The value will be loaded in variable $line

For printing the process id you need to add this line

pid=`echo $line | awk '{print $1}'`;

So the entire script will look like this

top -b -n 1 |grep java|while read -r line ; do
echo "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+";
echo "Processing Each line Now ->  $line"
echo "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+";
pid=`echo $line | awk '{print $1}'`;
echo "The PID is $pid";
# Main Program Goes Here
done

Hope this helps 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *