首页 > 解决方案 > 用于获取特定用户 ID 和进程计数的 Bash 脚本

问题描述

我需要 bash 脚本来计算特定用户或所有用户的进程。我们可以输入 0、1 或更多参数。例如

./myScript.sh root deamon

应该像这样执行:

root      92
deamon     8
2 users has total processes: 100

如果未输入任何参数,则应列出所有用户:

uuidd      1
awkd       2
daemon     1
root     210
kklmn      6
  5 users has total processes: 220

到目前为止,我所拥有的是适用于所有用户的脚本,并且运行良好(带有一些警告)。我只需要输入参数的部分(某种过滤结果)。这是所有用户的脚本:

cntp = 0  #process counter
cntu = 0  #user counter

ps aux |
awk 'NR>1{tot[$1]++; cntp++}
     END{for(id in tot){printf "%s\t%4d\n",id,tot[id]; cntu++} 
     printf "%4d users has total processes:%4d\n", cntu, cntp}'

标签: linuxbash

解决方案


#!/bin/bash

users=$@
args=()
if [ $# -eq 0 ]; then
  # all processes
  args+=(ax)
else
  # user processes, comma-separated list of users
  args+=(-u${users// /,})
fi

# print the user field without header
args+=(-ouser=)

ps "${args[@]}" | awk '
  { tot[$1]++ }
  END{ for(id in tot){ printf "%s\t%4d\n", id, tot[id]; cntu++ }
  printf "%4d users has total processes:%4d\n", cntu, NR}'

ps参数存储在数组中,args并在表单中列出所有进程ax或用户进程,-uuser1,user2 并且-ouser=只列出没有标题的用户字段。

awk脚本中,我只删除了可以替换为的NR>1测试和变量。cntpNR

可能的调用:

./myScript.sh
./myScript.sh root daemon
./myScript.sh root,daemon

推荐阅读