通过命令行在Linux中查找进程数 [英] Finding process count in Linux via command line
问题描述
我一直在寻找通过Linux中的命令行查找具有相同名称的正在运行的进程数的最佳方法.例如,如果我想查找正在运行的bash进程的数量并获得"5".当前,我有一个脚本执行'pidof',然后对标记化字符串进行计数.这工作正常,但我想知道是否有更好的方法可以完全通过命令行来完成.在此先感谢您的帮助.
I was looking for the best way to find the number of running processes with the same name via the command line in Linux. For example if I wanted to find the number of bash processes running and get "5". Currently I have a script that does a 'pidof ' and then does a count on the tokenized string. This works fine but I was wondering if there was a better way that can be done entirely via the command line. Thanks in advance for your help.
推荐答案
在具有pgrep
可用的系统上,-c
选项返回与给定名称匹配的进程数的计数
On systems that have pgrep
available, the -c
option returns a count of the number of processes that match the given name
pgrep -c command_name
请注意,这是grep
样式的匹配,而不是完全匹配,例如pgrep sh
也将匹配bash
进程.如果您希望完全匹配,还可以使用-x
选项.
Note that this is a grep
-style match, not an exact match, so e.g. pgrep sh
will also match bash
processes. If you want an exact match, also use the -x
option.
如果pgrep
不可用,则可以使用ps
和wc
.
If pgrep
is not available, you can use ps
and wc
.
ps -C command_name --no-headers | wc -l
ps
的-C
选项以command_name
作为参数,并且程序打印有关可执行文件名与给定命令名匹配的进程的信息表.这是完全匹配,不是grep
样式. --no-headers
选项禁止显示表的标题,通常将其打印为第一行.使用--no-headers
,每个匹配的进程只有一行.然后wc -l
计数并打印输入中的行数.
The -C
option to ps
takes command_name
as an argument, and the program prints a table of information about processes whose executable name matches the given command name. This is an exact match, not grep
-style. The --no-headers
option suppresses the headers of the table, which are normally printed as the first line. With --no-headers
, you get one line per process matched. Then wc -l
counts and prints the number of lines in its input.
这篇关于通过命令行在Linux中查找进程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!