Bash script find logged in user name using users | grep command

grep
bash

#1

You all would have the right to call me Bozo its ok.

I am really not bad at bash, but the simplest things just take my wickets sometimes. This is a part of a daemon for an @reboot script I am forced to write since cron decides not to have @reboot available for useraccounts, missing probably the most important user space functionality. Dont know whats up with the cronfolks. I have the really difficult issues in the script sorted out, but stumble over the following triviality.

There are still somethings I dont understand about command substituion and also things related to simple evaluation of variables from commands.
I want to settle this triviality once and for all.

Say for example we have root mo and curly as users logged in
Set
username="$(whoami)" #Lets say we are mo
loggedin=$(users |grep -i $username)

Now here is where I get confused.
$] $ loggedin
mo
Which is exactly what I want,
but
$] “$ loggedin”
root mo curly
Looking at how loggedin is defined this should JUST BE moe

This is not what I want as I want a text string to use in conditions
eg
[ “$username” = “$loggedin” ] should equate mo with mo and be true.
At the moment it equates as false because of al the root and curly eroneously in “$loggedin”

So question is
How do I force a variable such as loggedin to only contain user moas the output of $(users |grep -i $username)
Meaning it should only give mo. when I execute “loggedin”


#2

To get current username running script, simply use $USER variable:

echo "$USER"

#3

Maybe I didnt explain it too well.

What I need is for $loggedin to give output such that “$loggedin” resolves to only mo when executed. Problem is that $login gives mo but “$loggedin” gives root mo curly. in the example below.
I dont know how to fix this that by some bash wizardry “$loggedin” can become the same as $loggedin. I need that as I need to evaluate as strings.
username="$(whoami)" #Lets say we are mo
loggedin=$(users |grep -i $username)


#4

Try:

loggedin="$(users |grep -io $username)"

#5

Hi,

username="$(whoami)"
loggedin="$(users | grep -io $username)"

Worked for me, Ubuntu Mate 18.04
bash --version

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
history -a; history -n; history -a; history -n; 

Regards