Reputation: 15
I would like to tell if a user is logged in or not.
if [ "$(who | grep -wq "$1")" == 0 ]
echo $1 "is logged in"
"$(who | grep -w "$1")"
is equal to 0 if grep finds $1 (a username) in the list(who). So if the user is in the list, he or she is logged in.
What is wrong with this?
Upvotes: 0
Views: 59
Reputation: 3596
In bash, $?
is used to save the exit code. you can use it to check the exit code of grep.
who | grep -wq "$1"
if [ $? -eq 0 ]; then
echo "$1 is logged in"
fi
Upvotes: 0
Reputation: 361729
grep doesn't print 0, which is what your script checks for. Its exit code is 0. To check the exit code it's simply:
if who | grep -wq "$1"; then
echo "$1 is logged in"
fi
Upvotes: 3