current logged in user

Hey guys

I need a script that reads a login name and verifies if that user is currently logged in

i have found few commands like "who" and "users"

but i wonder how can i verify it that login name is logged in or not?

"users" command would be the best choice as it only outputs the usernames without extra useless text.

Username may contain a dot that requires extra handling in regular expression, so I think use a loop to compare the string is easier than using grep.

#!/bin/bash

user="$1"
found=0

for i in `users`; do
    if [ "$i" == "$user" ]; then
        found=1
        break
    fi
done

if [ "$found" -eq 1 ]; then
    echo "User logged in."
else
    echo "User not logged in."
fi
1 Like

thx
can u explain me how did u use that loop plz ?

I use for loop in my script. It reads the data from the "users" command. Usernames are separated by a space, so "for" will treat it as a list of items. Then I compare each item in the list with the input argument "$user".

for i in `users`; do
    if [ "$i" == "$user" ]; then
        found=1
        break
    fi
done
1 Like