首页 > 解决方案 > pgrep 进程计数显示额外计数

问题描述

我有一个脚本名称 server.sh

  #!/bin/bash
 
  process_count=$(ps aux | grep server.sh | grep -v grep | wc -l )
  echo "total process running:"
  echo $process_count

... other script code

当我运行脚本时,我得到的输出为

./server.sh
total process running:
2

为什么我的进程计数为 2 而不是 1?我只运行了一个脚本,并且还排除了 grep 进程。即使使用 pgrep -f server.sh 并排除 pgrep 也会给出 2 作为进程计数。

标签: bashsh

解决方案


My approach is to redirect the output of ps into a temp file, then grep that file. That will eliminate extra processes.

ps aux > /tmp/ps.txt
process_count=$(grep server.sh /tmp/ps.txt | wc -l)
rm /tmp/ps.txt

推荐阅读