Getting PID of process in Shell Script

ぐ巨炮叔叔 提交于 2019-12-02 23:24:58

Just grep away grep itself!

process_id=`/bin/ps -fu $USER| grep "ABCD" | grep -v "grep" | awk '{print $2}'`

Have you tried to use pidof ABCD ?

Its very straight forward. ABCD should be replaced by your process name.

#!/bin/bash

processId=$(ps -ef | grep 'ABCD' | grep -v 'grep' | awk '{ printf $2 }')
echo $processId

Sometimes you need to replace ABCD by software name. Example - if you run a java program like java -jar TestJar.jar & then you need to replace ABCD by TestJar.jar

ps has an option for that:

process_id=`/bin/ps -C ABCD -o pid=`

You can also do away with grep and use only awk.
Use awk's expression matching to match the process name but not itself.

/bin/ps -fu $USER | awk '/ABCD/ && !/awk/ {print $2}'
Sandeep Singh

You can use this command to grep the pid of a particular process & echo $b to print pid of any running process:

b=`ps -ef | grep [A]BCD | awk '{ printf $2 }'`
echo $b
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!