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;}')