linux - 用于获取特定用户 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}'
解决方案
#!/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
测试和变量。cntp
NR
可能的调用:
./myScript.sh
./myScript.sh root daemon
./myScript.sh root,daemon
推荐阅读
- mysql - SQL:INNER JOIN,仅在右表中的所有行都满足条件时才返回结果
- kubernetes - 无法访问 Kubernetes 集群
- powershell - 使用 FBX2glTF 将多个 FBX 转换为 glTF
- git - 删除缓存在 git 中的大文件(文件名中有空格)
- flutter - 如何使用测试驱动程序在颤振中测试导航?
- mongodb - mongodb 服务器总是写在磁盘上
- java - 如何使用 Eclipse 减少 Java 中类似模式构建器的复杂代码的缩进
- netbeans - Netbeans 11 终端“无法启动 pty 进程:”
- python - Python shutil.copyfile 名称长度限制
- dart - 如何初始化 pubspec.yaml?