I run myscript.sh
scheduled in the root crontab and I need it to detect the non-root user (with which the system starts).
I have tried these variants:
local_user=${who -m | awk '{print $1;}'}
local_user=${logname 2>/dev/null || echo $SUDO_USER}
local_user=$(logname)
local_user=$(ps -o user= -p $$)
local_user=${SUDO_UID:-$(id -u)}
local_user=$(id -u $(logname))
if [ "$EUID" -eq 0 ]; then
local_user=$SUDO_USER
else
local_user=$(whoami)
fi
# or
if [ -n "$SUDO_USER" ]; then
local_user="$SUDO_USER"
else
local_user="$(whoami)"
fi
The only ones that work are:
local_user=${SUDO_USER:-$(whoami)}
local_user=${SUDO_USER:-$USER}
but they only work if I run the script manually, either with sudo or from root account, but it doesn't work in crontab root.
example:
#!/bin/bash
local_user=${SUDO_USER:-$(whoami)}
echo "my user is $local_user" | tee /var/log/syslog
# run crontab
*/1 * * * * /home/user/test/test.sh
my user is root
# run manual
root@foo:/home/user/test# ./test.sh
my user is user
any idea?
PD: ubuntu 22.04
Update: solved!
I found here: https://unix.stackexchange.com/a/617686/266428
local_user=$(ps -eo user,uid | awk 'NR>1 && $2 >= 1000 && ++seen[$2]==1{print $1}')
or
local_user=$(who | head -1 | awk '{print $1;}')
Who exactly is the logged on user for
cron
running asroot
?root
. The reason the scripts work manually is because there is asudo
in play from a logged on user. There is none incron
, the system launches the job in the specified context, which here isroot
. And there in fact doesn't have to be a logged in user whencron
runs, everyone can be logged out and it will still run, creating the necessary context for each job. Also, unlike Windows, Linux does not limit you to one logged-in user; you can have dozens of users all logged in at the same time (though with consumer grade hardware, they'll all find it pretty sluggish if they do that). The best you can do is to ask the system for the current list of logged-in users.