Question

I need a little help to finish off a little code. I want to do a query with the who command, but I only want to see the users listed I give in arguments with username and pts/num, ordered by the time of login. It works for 1 user, but I would like to get it work with more users. Here it is atm:

#!/bin/bash
who |
awk '($1 ~ /'$*'/){print $3 $4" "$1" "$2}' |
sort -n |
awk '{ print $2, $3 }'

How can I make it work with multiple users?

Sample use:

./script username1 username2 blabla pete stevie
Was it helpful?

Solution

If I get you correct than for:

$ who
oxo    tty7         2014-05-12 14:32 (:0)
bar    pts/5        2014-05-12 18:35 (:0:S.1)
oxo    pts/1        2014-05-13 13:29 (:0:S.5)
baz    pts/8        2014-05-12 18:35 (:0:S.2)
oxo    pts/12       2014-05-12 18:35 (:0:S.3)
oxo    pts/13       2014-05-12 18:35 (:0:S.4)
foo    pts/15       2014-05-12 18:35 (:0:S.0)
bar    pts/17       2014-05-13 19:36 (:0:S.6)
bar    pts/18       2014-05-14 00:03 (:0:S.7)

you expect to get for example:

$ ./who.sh foo bar
bar pts/5
foo pts/15
bar pts/17
bar pts/18

If so than this will work for you:

#!/bin/bash    
users=`echo $@|tr " " "|"`
who|sort -k 3|awk -v users="$users" '$1 ~ users {print $1" "$2}'

Actually it could be done just in the awk witout any tr or sort but I hope it's good enough.

UPDATE:

To get rid of tr this can be used:

#!/bin/bash
who|sort -k 3|awk -v users="$*" 'BEGIN { regex = gensub(/\s/, "|" ,"g", users) }; $1 ~ regex { print $1" "$2 }'

You can use asorti() to replace sort.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top