TransWikia.com

Is there a awk command for searching if a user is logged on?

Unix & Linux Asked by Darunia on December 22, 2021

I’m not sure how awk could allow you to view if someone is online since it’s used for manipulating text files. I know how to do it with the grep command which is like

 who | grep 'name'

and then it would show if that person logged in. The syntax for awk is

awk options 'selection _criteria {action }' input-file

How would you be able to find someone using awk if it’s usually used for manipulating files?

2 Answers

#! /bin/sh -

is_logged_in() {
  who | USER=$1 awk -v ret=1 '
    $1"" == ENVIRON["USER"]"" {ret = 0; exit}
    END {exit(ret)}'
}

if is_logged_in root; then
  echo root is logged in
fi

That defines a is_logged_in shell function, that takes a user name as argument. We feed the output of who to awk to which we've passed the function argument in the USER environment variable.

The awk code processes each record in turn. If the first field in the record is equal to the value of that environment variable (here appending "" to operands to force a string comparison), then we exit with a 0 (success) exit status.

That function can then be used in if statements to check whether a user is logged in.

Answered by Stéphane Chazelas on December 22, 2021

Just an example of one of the possible ways to use awk and external commands:

is_logged($1) { print $1, "is present!"}

function is_logged(x,a){                     ## a local var
  "who|grep -w " x | getline a
  return a
}

And then:

$ awk -f test
abc
Darunia

--> Darunia is present!

Answered by JJoao on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP