Linux 在 Shell 脚本中获取进程的 PID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16965089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:09:22  来源:igfitidea点击:

Getting PID of process in Shell Script

linuxshellunixpid

提问by Mayank Jain

I am writing one shell script and I want to get PID of one process with name as "ABCD". What i did was :

我正在编写一个 shell 脚本,我想获取一个名称为“ABCD”的进程的 PID。我所做的是:

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

This gets PID of two processes i.e. 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.

请建议。

采纳答案by blue

Just grep away grep itself!

只需 grep 即可 grep 本身!

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

回答by wizard

Have you tried to use pidof ABCD?

你试过用pidof ABCD吗?

回答by Sandeep Singh

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

您可以使用此命令 grep 特定进程的 pid & echo$b打印任何正在运行的进程的 pid:

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

回答by Rejuan

It's very straight forward. ABCDshould be replaced by your process name.

这是非常直接的。ABCD应替换为您的进程名称。

#!/bin/bash

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

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

有时您需要用软件名称替换ABCD。示例 - 如果您运行这样的 Java 程序,java -jar TestJar.jar &则需要将ABCD替换为TestJar.jar

回答by Salvador Fonseca

ps has an option for that:

ps 有一个选项:

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

回答by Gino Mempin

You can also do away with grepand use only awk.
Use awk's expression matchingto match the process name but not itself.

您也可以取消grep并仅使用awk.
使用awk表达式匹配来匹配进程名称而不是它本身。

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