bash 以 root 身份运行脚本时获取用户主目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7358611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get users home directory when they run a script as root
提问by Peter-W
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?
我有一个需要以 root 身份运行的 sh 脚本,但是它由最终用户使用 sudo 运行。使用 sudo 运行时,如何在 ~/ 指向 /root 时获取用户主目录?
采纳答案by dogbane
The user's home directory would be ~$SUDO_USER
. You can use eval
as follows:
用户的主目录将是~$SUDO_USER
. 您可以eval
按如下方式使用:
USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}
回答by Micha? ?rajer
回答by glglgl
$ 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
.
因此,您可以$SUDO_USER
使用getent passwd $SUDO_USER | cut -d: -f6
.
回答by Missaka Wijekoon
Try accessing the environment variable $SUDO_USER
尝试访问环境变量 $SUDO_USER
回答by Hai Vu
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:
除非我误解了这个问题,否则当用户使用 sudo 运行脚本时,$HOME
环境变量不会改变。为了测试,我创建了这个脚本:
#!/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).
输出告诉我它$HOME
仍然指向用户的家(在本例中为/home/haiv)。