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 sudo?
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.
The user's home directory would be ~$SUDO_USER
. You can use eval
as follows:
USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}
$ 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
.
Try accessing the environment variable $SUDO_USER
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).
It comes to a little improvement for the eval solution.
Before sending the username variable to eval
, test it with the user existence, so if there's arbitrary code, it won't pass the check.
#? Description:
#? Get the user's home directory by username regardless of whether is running with `sudo`.
#? The username is checked, it must exist, to avoid the arbitrary code execution of `eval`.
#? The returned home directory's existence is not checked.
#?
#? Usage:
#? @home USERNAME
function home () {
if id "$1" >/dev/null 2>&1; then
eval echo "~$1"
else
return 255
fi
}
Run the code on macOS:
$ home root
Output:
/var/root
If you run it with something like:
home 'root ; ls'
It gives nothing and returns an error, the ls
won't be executed.
You can use Hai's incomplete answer to very simply construct the user's home directory. He and others correctly state that you can get the original user while in the sudo shell. You can use that to construct the home directory into a new variable called user_home (or whatever you like):
#user_home="/home/${$SUDO_USER}";
精彩评论