我一直在寻找通过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 -lps的-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中查找进程数
发布评论