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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:01:17  来源:igfitidea点击:

Get users home directory when they run a script as root

bashshell

提问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 evalas follows:

用户的主目录将是~$SUDO_USER. 您可以eval按如下方式使用:

USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}

回答by Micha? ?rajer

Try to avoid eval. Especially with root perms.

尽量避免 eval。尤其是根烫。

You can do:

你可以做:

USER_HOME=$(getent passwd $SUDO_USER | cut -d: -f6)

Update:

更新:

hereis why to avoid eval.

就是为什么要避免 eval。

回答by glglgl

$ sudo env |grep USER
USER=root
USERNAME=root
SUDO_USER=glglgl

So you can access $SUDO_USERand 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 $HOMEenvironment 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 $HOMEis still pointing to the user's home (in this case, /home/haiv).

输出告诉我它$HOME仍然指向用户的家(在本例中为/home/haiv)。