Bash脚本以获取特定用户的ID和进程数 [英] Bash script to get specific user(s) id and processes count

查看:79
本文介绍了Bash脚本以获取特定用户的ID和进程数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need bash script to count processes of SPECIFIC users or all users. We can enter 0, 1 or more arguments. For example

./myScript.sh root deamon

应该这样执行:

root      92
deamon     8
2 users has total processes: 100

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

If nothing is entered as parameter, then all users should be listed:

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

到目前为止,我所拥有的是适用于所有用户的脚本,它可以正常工作(带有一些警告).我只需要在其中输入参数的部分(某种过滤结果).这是所有用户的脚本:

What I have till now is script for all users, and it works fine (with some warnings). I just need part where arguments are entered (some kind of filter results). Here is script for all users:

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的形式列出所有带有 ax 的进程或用户进程,user2 -ouser = 仅列出不带标题的用户字段.

The ps arguments are stored in array args and list either all processes with ax or user processes in the form -uuser1,user2 and -ouser= only lists the user field without header.

awk 脚本中,我仅删除了 NR> 1 测试和变量 cntp ,可以将其替换为 NR .

In the awk script I only removed the NR>1 test and variable cntp which can be replaced by NR.

可能的调用:

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

这篇关于Bash脚本以获取特定用户的ID和进程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆