Command to check if the user is logged in?

chrisdaggett
Contributor II

I am making a simple bash script. I want to use an IF statement that checks to make sure the user is logged in before it runs (else Exit).

Anyone know what command line to use to make sure the computer is not at the login window, or that a user is logged in?

Thanks in advance.

2 ACCEPTED SOLUTIONS

maxbehr
Contributor II

Agree, I'm sure there is probably a more elegant way but I just use

who | grep "console"

if that returns anything then you know a user is logged in.

View solution in original post

iJake
Valued Contributor
currentUser=$(stat -f %Su "/dev/console")

if [[ "$currentUser" == "root" ]]; then
exit
fi

View solution in original post

4 REPLIES 4

bvrooman
Valued Contributor

You can gather that information from who. There might be a better way to do it, though.

maxbehr
Contributor II

Agree, I'm sure there is probably a more elegant way but I just use

who | grep "console"

if that returns anything then you know a user is logged in.

iJake
Valued Contributor
currentUser=$(stat -f %Su "/dev/console")

if [[ "$currentUser" == "root" ]]; then
exit
fi

chrisdaggett
Contributor II

Thanks all :).