![](/img/trans.png)
[英]A bash script that monitors number of processes per user count all processes for each user ID with the number of processes running
[英]Bash script to get specific user(s) id and processes count
我需要 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
並以-uuser1,user2
和-ouser=
的形式列出所有帶有ax
進程或用戶進程-uuser1,user2
而-ouser=
僅列出沒有標題的用戶字段。
在awk
腳本中,我只刪除了NR>1
測試和可以由NR
替換的變量cntp
。
可能的調用:
./myScript.sh
./myScript.sh root daemon
./myScript.sh root,daemon
以下似乎有效:
ps axo user |
awk -v args="$(IFS=,; echo "$*")" '
BEGIN {
# split args on comma
split(args, users, ",");
# associative array with user as indexes
for (i in users) {
enabled[users[i]] = 1
}
}
NR > 1 {
tot[$1]++;
cntp++;
}
END {
for(id in tot) {
# if we passed some arguments
# and its disabled
if (length(args) && enabled[id] == 0) {
continue
}
printf "%s\t%4d\n", id, tot[id];
cntu++;
}
printf "%4d users has total processes:%4d\n", cntu, cntp
}
'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.