vlada
vlada

Reputation: 167

Bash script to get specific user(s) id and processes count

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

should execute like this:

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}'

Upvotes: 0

Views: 754

Answers (2)

Freddy
Freddy

Reputation: 4688

#!/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}'

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.

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

Possible invocations:

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

Upvotes: 3

KamilCuk
KamilCuk

Reputation: 141060

The following seems to work:

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
    }
'

Tested in repl.

Upvotes: 1

Related Questions