简体   繁体   English

在 Shell 脚本中获取进程的 PID

[英]Getting PID of process in Shell Script

I am writing one shell script and I want to get PID of one process with name as "ABCD".我正在编写一个 shell 脚本,我想获取一个名称为“ABCD”的进程的 PID。 What i did was :我所做的是:

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

This gets PID of two processes ie of process ABCD and the GREP command itself what if I don't want to get PID of GREP executed and I want PID only of ABCD process?这将获取两个进程的 PID,即进程 ABCD 的 PID 和 GREP 命令本身,如果我不想执行 GREP 的 PID 而我只想要 ABCD 进程的 PID,该怎么办?

Please suggest.请建议。

只需 grep 即可 grep 本身!

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

您是否尝试过使用pidof ABCD

It's very straight forward.这是非常直接的。 ABCD should be replaced by your process name. ABCD应替换为您的进程名称。

#!/bin/bash

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

Sometimes you need to replace ABCD by software name.有时您需要用软件名称替换ABCD Example - if you run a java program like java -jar TestJar.jar & then you need to replace ABCD by TestJar.jar .示例 - 如果您运行像java -jar TestJar.jar &这样的java程序java -jar TestJar.jar &那么您需要用TestJar.jar替换ABCD

ps 有一个选项:

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

You can also do away with grep and use only awk .您也可以取消grep并仅使用awk
Use awk 's expression matching to match the process name but not itself.使用awk表达式匹配来匹配进程名称而不是它本身。

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

You can use this command to grep the pid of a particular process & echo $b to print pid of any running process:您可以使用此命令来 grep 特定进程的 pid & echo $b以打印任何正在运行的进程的 pid:

b=`ps -ef | grep [A]BCD | awk '{ printf $2 }'`
echo $b

ps | pgrep ABCD

可以尝试上面的命令返回ABCD进程的进程id。

我找到了一个更好的方法来做到这一点。

top -n 1 | grep "@#" | grep -Eo '^[^ ]+' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM