How to use the linux shell pgrep command (pgrep command) to obtain the process number and count the number of processes (learn to distinguish Linux process process names)

Problem background

According to my previous method, in a script, I get the process number with the same name as the script in addition to the script's own process:

ps -ef | grep "${SCRIPT_NAME}" | grep -v "grep" | awk '{print $2}' | grep -v "$PID"

There is a big problem with this method. Inexplicably, it cannot filter out the grep process normally (it is a bit complicated here, and I couldn’t figure it out for a while. It is said that grep can open child processes, not the grep process. Subprocess, but opened a process that is the same as the script, causing problems. For specific reference: Problems with creating subprocesses when linux shell scripts execute commands (in certain situations, such as background running, pipes, branches or subshells, etc., the script may A child process will be created to execute the command) grep )

Later, I switched to the pgrep command. The advantage of using this command is that there is no need to use the grep command. It directly finds the process number and does not bring in additional process numbers. Let's take a look at the specific usage of the pgrep command.

pgrep command

The pgrep command is used to find and list matching process IDs (PIDs) based on a process's name or other attributes. It allows flexible process finding and filtering based on different options.

help documentation

root@ubuntu:/ky/boot# pgrep --help

Usage:
 pgrep [options] <pattern>

Options:
 -d, --delimiter <string>  specify output delimiter
 -l, --list-name           list PID and process name
 -a, --list-full           list PID and full command line
 -v, --inverse             negates the matching
 -w, --lightweight         list all TID
 -c, --count               count of matching processes
 -f, --full                use full process name to match
 -g, --pgroup <PGID,...>   match listed process group IDs
 -G, --group <GID,...>     match real group IDs
 -i, --ignore-case         match case insensitively
 -n, --newest              select most recently started
 -o, --oldest              select least recently started
 -P, --parent <PPID,...>   match only child processes of the given parent
 -s, --session <SID,...>   match session IDs
 -t, --terminal <tty,...>  match by controlling terminal
 -u, --euid <ID,...>       match by effective IDs
 -U, --uid <ID,...>        match by real IDs
 -x, --exact               match exactly with the command name
 -F, --pidfile <file>      read PIDs from file
 -L, --logpidfile          fail if PID file is not locked
 -r, --runstates <state>   match runstates [D,S,Z,...]
 --ns <PID>                match the processes that belong to the same
                           namespace as <pid>
 --nslist <ns,...>         list which namespaces will be considered for
                           the --ns option.
                           Available namespaces: ipc, mnt, net, pid, user, uts

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see pgrep(1).

Chinese translation:

root@ubuntu:/ky/boot# pgrep --help

用法:
 pgrep [选项] <模式>

选项:
 -d, --delimiter <字符串>  指定输出分隔符
 -l, --list-name           列出PID和进程名称
 -a, --list-full           列出PID和完整命令行
 -v, --inverse             反转匹配结果
 -w, --lightweight         列出所有TID
 -c, --count               统计匹配进程的数量
 -f, --full                使用完整进程名称进行匹配
 -g, --pgroup <PGID,...>   匹配指定的进程组ID
 -G, --group <GID,...>     匹配真实组ID
 -i, --ignore-case         不区分大小写进行匹配
 -n, --newest              选择最近启动的进程
 -o, --oldest              选择最早启动的进程
 -P, --parent <PPID,...>   仅匹配给定父进程的子进程
 -s, --session <SID,...>   匹配会话ID
 -t, --terminal <tty,...>  通过控制终端进行匹配
 -u, --euid <ID,...>       通过有效ID进行匹配
 -U, --uid <ID,...>        通过真实ID进行匹配
 -x, --exact               精确匹配命令名称
 -F, --pidfile <文件>      从文件中读取PID
 -L, --logpidfile          如果PID文件未锁定,则失败
 -r, --runstates <状态>    匹配运行状态 [D,S,Z,...]
 --ns <PID>                匹配与<pid>相同命名空间的进程
 --nslist <ns,...>         列出将用于--ns选项的命名空间
                           可用的命名空间:ipc, mnt, net, pid, user, uts

 -h, --help     显示此帮助信息并退出
 -V, --version  输出版本信息并退出

更多详细信息请参阅pgrep(1)

Note that the above <pattern>is a pattern of process names or other attributes to match. It can be replaced with a specific value based on the actual situation.

Usage example

The following are pgrepexamples of usage of different options of the command:

We test in this container:

Note: We must first learn to distinguish what is the process name of a process!
The process name is the executable file of that process. There is only one process name. Except for the process name, everything else is the path and parameters.
For example /bin/bash /usr/local/bin/entrypoint.sh, the process name isbash

root@5940438e0ee6:/build/libevent# echo "=====输出所有进程完整进程信息:"
=====输出所有进程完整进程信息:
root@5940438e0ee6:/build/libevent# ps -ef 
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 Jun27 pts/0    00:00:00 /bin/bash /usr/local/bin/entrypoint.sh
root           7       1  0 Jun27 pts/0    00:02:56 ./kyai_rest
root          43       0  0 23:38 pts/1    00:00:00 /bin/bash
root          56      43  0 23:40 pts/1    00:00:00 ps -ef
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# echo "输出所有进程进程名:"
=====输出所有进程进程名:
root@5940438e0ee6:/build/libevent# ps -e -o comm=
bash
kyai_rest
bash
ps
root@5940438e0ee6:/build/libevent# 

1. List the PID and process name of the matching process (-l) (by default, only a subset of the process name can be matched. If you want to use a subset of the complete process name, please add the -f parameter. The same below. )

pgrep -l <pattern>
pgrep --list-name <pattern>

Example:

root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -l ky
7 kyai_rest
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -l ./
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -l ./ky
root@5940438e0ee6:/build/libevent#
root@5940438e0ee6:/build/libevent# pgrep -l -f ./ky
7 kyai_rest

2. List the PID and complete command line of matching processes (-a)

pgrep -a <pattern>
pgrep --list-full <pattern>

Example:

root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -a ky
7 ./kyai_rest
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -a ./ky
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -a -f ./ky
7 ./kyai_rest
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -af ./ky
7 ./kyai_rest
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -a bash
1 /bin/bash /usr/local/bin/entrypoint.sh
43 /bin/bash
root@5940438e0ee6:/build/libevent# 

3. Count the number of matching processes (-c)

pgrep -c <pattern>
pgrep --count <pattern>

Example:

root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -c ky
1
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -c bash
2
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -c ./ky
0
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -c -f ./ky
1
root@5940438e0ee6:/build/libevent# 

4. Use a subset of the complete process name (including parameters) for matching (-f) (if the pattern spans process commands and parameters, it needs to be enclosed in double quotes) ★★★★★

pgrep -f <pattern>
pgrep --full <pattern>

For example, if there is a process with the full name python3 -u /ky/alg/kyai/nv/m/people/alg/main.py, use:

pgrep -f <pattern>

Pattern is any string subset of the full name of the process and can be matched.

Example 1
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -f ky
7
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -f ./ky
7
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep ./ky
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep /usr/local/bin/entrypoint.sh
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -f /usr/local/bin/entrypoint.sh
1
root@5940438e0ee6:/build/libevent# 

Example 2

Insert image description here

5. Match case-insensitively (-i)

pgrep -i <pattern>
pgrep --ignore-case <pattern>

Example:

root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -i KyAi
7
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -i entry
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -i -f eNtry
1
root@5940438e0ee6:/build/libevent# 

6. Select the most recently started process (n)

pgrep -n <pattern>
pgrep --newest <pattern>

Example:

root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -a bash
1 /bin/bash /usr/local/bin/entrypoint.sh
43 /bin/bash
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -a -n bash
43 /bin/bash
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -n bash
43
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# 

7. Select the earliest started process (-o)

pgrep -o <pattern>
pgrep --oldest <pattern>

Example:

root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -a bash
1 /bin/bash /usr/local/bin/entrypoint.sh
43 /bin/bash
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -a -o bash
1 /bin/bash /usr/local/bin/entrypoint.sh
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -o bash
1
root@5940438e0ee6:/build/libevent# 

8. Match only child processes of a given parent process (-P)

pgrep -P <PPID> <pattern>
pgrep --parent <PPID> <pattern>

Example:

For example, process No. 0 has two sub-processes No. 1 and No. 2:

Insert image description here

Use pgrep -P 0the following command to find the child processes of process 0:

root@ubuntu:~# 
root@ubuntu:~# pgrep -P 0
1
2
root@ubuntu:~# 

Filter child processes when found:

root@ubuntu:~# 
root@ubuntu:~# pgrep -P 0 "system"
1
root@ubuntu:~# 
root@ubuntu:~# pgrep -P 0 "thread"
2
root@ubuntu:~# 
root@ubuntu:~# 

Note: When sometimes using the -f parameter to match and filter from string segments that are not process names, pay attention to the use of double quotes, and issues that should still be paid attention to after using double quotes:

In the following test: pgrep -f -P 0 --systemand pgrep -f -P 0 "--system"both reported errors, only pgrep -f -P 0 " --system"there was no problem.

root@ubuntu:~# 
root@ubuntu:~# pgrep -f -P 0 --system
pgrep: unrecognized option '--system'

Usage:
 pgrep [options] <pattern>

Options:
 -d, --delimiter <string>  specify output delimiter
 -l, --list-name           list PID and process name
 -a, --list-full           list PID and full command line
 -v, --inverse             negates the matching
 -w, --lightweight         list all TID
 -c, --count               count of matching processes
 -f, --full                use full process name to match
 -g, --pgroup <PGID,...>   match listed process group IDs
 -G, --group <GID,...>     match real group IDs
 -i, --ignore-case         match case insensitively
 -n, --newest              select most recently started
 -o, --oldest              select least recently started
 -P, --parent <PPID,...>   match only child processes of the given parent
 -s, --session <SID,...>   match session IDs
 -t, --terminal <tty,...>  match by controlling terminal
 -u, --euid <ID,...>       match by effective IDs
 -U, --uid <ID,...>        match by real IDs
 -x, --exact               match exactly with the command name
 -F, --pidfile <file>      read PIDs from file
 -L, --logpidfile          fail if PID file is not locked
 -r, --runstates <state>   match runstates [D,S,Z,...]
 --ns <PID>                match the processes that belong to the same
                           namespace as <pid>
 --nslist <ns,...>         list which namespaces will be considered for
                           the --ns option.
                           Available namespaces: ipc, mnt, net, pid, user, uts

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see pgrep(1).
root@ubuntu:~# 
root@ubuntu:~# pgrep -f -P 0 "--system"
pgrep: unrecognized option '--system'

Usage:
 pgrep [options] <pattern>

Options:
 -d, --delimiter <string>  specify output delimiter
 -l, --list-name           list PID and process name
 -a, --list-full           list PID and full command line
 -v, --inverse             negates the matching
 -w, --lightweight         list all TID
 -c, --count               count of matching processes
 -f, --full                use full process name to match
 -g, --pgroup <PGID,...>   match listed process group IDs
 -G, --group <GID,...>     match real group IDs
 -i, --ignore-case         match case insensitively
 -n, --newest              select most recently started
 -o, --oldest              select least recently started
 -P, --parent <PPID,...>   match only child processes of the given parent
 -s, --session <SID,...>   match session IDs
 -t, --terminal <tty,...>  match by controlling terminal
 -u, --euid <ID,...>       match by effective IDs
 -U, --uid <ID,...>        match by real IDs
 -x, --exact               match exactly with the command name
 -F, --pidfile <file>      read PIDs from file
 -L, --logpidfile          fail if PID file is not locked
 -r, --runstates <state>   match runstates [D,S,Z,...]
 --ns <PID>                match the processes that belong to the same
                           namespace as <pid>
 --nslist <ns,...>         list which namespaces will be considered for
                           the --ns option.
                           Available namespaces: ipc, mnt, net, pid, user, uts

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see pgrep(1).
root@ubuntu:~# 
root@ubuntu:~# 
root@ubuntu:~# pgrep -f -P 0 " --system"
1
root@ubuntu:~# 
root@ubuntu:~# 

9. Match via control terminal (-t)

use

One use for searching by specifying a specific terminal name is to narrow the scope of the search. In a multi-user or multi-terminal environment, there may be multiple terminals running the same process at the same time. By specifying a terminal name, you can search for matching processes only in a specific terminal, rather than in all terminals.

This is useful if you need to perform actions on a specific terminal or monitor processes on a specific terminal. For example, you might want to find processes for an application running on a specific terminal, or to find processes associated with a user on a specific terminal.

Additionally, specifying a terminal name can be used for process management in scripts or automated tasks. By specifying a specific terminal, you can ensure that operations are only performed on processes on that specific terminal, without affecting processes on other terminals.

In summary, specifying specific terminal names to search for provides more precise and targeted process discovery and management.

Order
pgrep -t <tty> <pattern>
pgrep --terminal <tty> <pattern>
Test steps

Follow these steps to test:

  1. Open a terminal.
  2. Run ttythe command to get the name of the current terminal. For example, if the terminal name is /dev/tty1, <tty>replace with tty1.
  3. Run pgrep -t <tty> <pattern>the command, <pattern>replacing with the process name or keyword you want to find. For example, if you want to find all running bashprocesses, run pgrep -t tty1 bash.
  4. If the command executes successfully, it will output the matching process ID.
  5. You can also try running pgrep --terminal <tty> <pattern>the command, which does the same thing as the above command.

Note that pgrepthe command is used to find matching processes in the process list and print their process IDs. <tty>is the terminal name, <pattern>is the process name or keyword to find. You need to replace these parameters according to your actual situation.

Example
root@ubuntu:~# 
root@ubuntu:~# tty
/dev/pts/0
root@ubuntu:~# 
root@ubuntu:~# 
root@ubuntu:~# pgrep -t /dev/pts/0 bash
root@ubuntu:~# 
root@ubuntu:~# pgrep -t /dev/pts/0 sy
root@ubuntu:~# 
root@ubuntu:~# pgrep -t /dev/pts/0
root@ubuntu:~# 
root@ubuntu:~# pgrep -t "/dev/pts/0"
root@ubuntu:~# 
root@ubuntu:~# pgrep -t "/dev/pts/0" bash
root@ubuntu:~# 
root@ubuntu:~# 

Embarrassing, I can’t find anything in this search

10. Match by valid ID (-u)

use

pgrep -u <ID> <pattern>The and pgrep --euid <ID> <pattern>commands are used to find matching processes under the specified user ID or effective user ID.

  • <ID>Parameters specify a user ID or a valid user ID. You can substitute the user's username or user ID <ID>.
  • <pattern>Parameters are used to specify the process name or keyword to find.
Order
pgrep -u <ID> <pattern>
pgrep --euid <ID> <pattern>
Test steps
  1. Open a terminal.
  2. Run idthe command to get the user ID and effective user ID of the current user. For example, if user ID is 1000and effective user ID is 1000, <ID>replace with 1000.
  3. Run pgrep -u <ID> <pattern>the command, <pattern>replacing with the process name or keyword you want to find. For example, if you want to find all running bashprocesses under the current user, you can run pgrep -u 1000 bash.
  4. If the command executes successfully, it will output the matching process ID.
  5. You can also try running pgrep --euid <ID> <pattern>the command, which does the same thing as the above command.

Note that pgrepthe command is used to find matching processes in the process list and print their process IDs. -uThe or --euidoption is used to specify a user ID or a valid user ID. <ID>is the user ID or effective user ID, <pattern>is the process name or keyword to be found. You need to replace these parameters according to your actual situation.

Example
root@ubuntu:~# 
root@ubuntu:~# id
uid=0(root) gid=0(root) groups=0(root)
root@ubuntu:~# 
root@ubuntu:~# 
root@ubuntu:~# pgrep -u 0000 bash
3058
3955
23187
root@ubuntu:~# 
root@ubuntu:~# pgrep -u 0 bash
3058
3955
23187
root@ubuntu:~# 
root@ubuntu:~# pgrep -u 1000 bash
root@ubuntu:~# 
root@ubuntu:~# ps -ef | grep bash
root        1061       1  0 19:27 ?        00:00:00 /bin/bash /etc/systemd/nvmemwarning.sh
root        1260       1  0 19:28 ?        00:00:00 /bin/bash /ky/boot/kyai_nv_server.sh
root        1276       1  0 19:28 ?        00:00:00 /bin/bash /etc/systemd/nvgetty.sh
root        3058    2914  0 19:28 pts/0    00:00:00 /bin/bash /usr/local/bin/entrypoint.sh
root        3955    3915  0 19:28 pts/0    00:00:00 /bin/bash /usr/local/bin/entrypoint.sh
root       23187   23106  0 21:46 pts/0    00:00:00 -bash
root       36607   23187  0 23:39 pts/0    00:00:00 grep --color=auto bash
root@ubuntu:~# 
root@ubuntu:~# 

Insert image description here

11. Match by real ID (-U)

For details, please refer to the effective id and real id. I don't understand it very well yet.

Order
pgrep -U <ID> <pattern>
pgrep --uid <ID> <pattern>
Example
root@ubuntu:~# 
root@ubuntu:~# pgrep -U 0000 bash
3058
3955
23187
root@ubuntu:~# 
root@ubuntu:~# 

12. Exactly match command name (-x)★★★

Order
pgrep -x <pattern>
pgrep --exact <pattern>
Example
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# ps -ef 
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 19:28 pts/0    00:00:00 /bin/bash /usr/local/bin/entrypoint.sh
root           8       1  0 19:28 pts/0    00:00:39 ./kyai_rest
root          41       0  0 23:45 pts/1    00:00:00 /bin/bash
root          54      41  0 23:46 pts/1    00:00:00 ps -ef
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x kyai 
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x kyai_rest
8
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x -f kyai_rest
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x -f ./kyai_rest
8
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x bash          
1
41
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x -f bash
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x -f /bin/bash
41
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x -f /bin/bash /usr/local/bin/entrypoint.sh
pgrep: only one pattern can be provided
Try `pgrep --help' for more information.
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# pgrep -x -f "/bin/bash /usr/local/bin/entrypoint.sh"
1
root@5940438e0ee6:/build/libevent# 
root@5940438e0ee6:/build/libevent# 

Note: Exact matches are all complete matches including parameters

Insert image description here

Guess you like

Origin blog.csdn.net/Dontla/article/details/131407327