【问题标题】:Get Number Of Running Processes By Name In Bash在 Bash 中按名称获取正在运行的进程数
【发布时间】:2020-07-10 18:14:55
【问题描述】:

假设我在终端中运行以下命令:

pgrep Google Chrome

它会产生以下所有 PID 的输出:

110
311
142

如果不计算自己产生的类似内容,我如何才能准确显示列出了多少进程:

110
311
142

There are currently 3 processes running under the application 'Google Chrome'

【问题讨论】:

  • pgrep 'Google Chrome' | wc -l
  • 顶部 | grep 谷歌浏览器 | uniq 类似这样的工作?

标签: bash macos terminal


【解决方案1】:

我发现包装函数对这类事情很有帮助:

pgrep() {
  local app=${!#} pids
  # now invoke the *command* pgrep and
  # capture the output into an array of lines
  readarray -t pids < <(command pgrep "$@")
  # print the output
  printf "%s\n" "${pids[@]}"
  # and print the summary
  printf "\nThere are currently %d processes running under the application '%s'\n" \
    "${#pids[@]}" \
    "$app"
}

这还允许您使用 pgrep 选项,例如 pgrep -fl "Google Chrome"

问题是 pgrep 允许你指定多个模式,而这个函数只捕获最后一个作为“应用程序”。

【讨论】:

    【解决方案2】:

    为了以您指定的格式生成输出:

    proc="Google Chrome"
    
    pids=$(pgrep "$proc")
    if [[ -n $pids ]]; then
        printf "%s\n\nThere are currently %d processes running under the application '%s'\n" \
            "$pids" "$(wc -l <<< "$pids")" "$proc"
    fi
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-27
      • 2014-01-18
      • 2012-09-05
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多