I have a sh script that needs to be run as root, however it is run by the end user using sudo. How can I get the users home directory when ~/ points to /root when running with s
$ sudo env |grep USER
USER=root
USERNAME=root
SUDO_USER=glglgl
So you can access $SUDO_USER
and ask the system for his homedir with getent passwd $SUDO_USER | cut -d: -f6
.
The user's home directory would be ~$SUDO_USER
. You can use eval
as follows:
USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}
Unless I misunderstood the question, when the user runs the script with sudo, the $HOME
environment variable does not change. To test out, I created this script:
#!/bin/bash
#sudo_user.sh
env | grep -e USER -e HOME
... and run it:
sudo ./sudo_user.sh
Output:
USER=root
HOME=/home/haiv
USERNAME=root
SUDO_USER=haiv
The output tells me that $HOME
is still pointing to the user's home (in this case, /home/haiv).
Try to avoid eval. Especially with root perms.
You can do:
USER_HOME=$(getent passwd $SUDO_USER | cut -d: -f6)
Update:
here is why to avoid eval.
Try accessing the environment variable $SUDO_USER