sudo
is receiving DISPLAY=:0
as the username, ie $user
is empty, which you can also see from your output at the end lacking the username (and the fact the uid changes when run with sudo). It depends on the success of the line above, but that seems to work since we get :0
What’s the output of who
?
# Generally IMO using "" is nicer and less error prone
# Also works without the () around $display, on my system at least
user=$(who | grep "($display)" | awk '{print $1}' | head -n 1)
However both that and your version work as expected for me, as my user, using sudo
and from root. (in both bash and zsh)
EDIT:
Oops, missed a line in root.
Removed mis-information.