Get users home directory when they run a script as

2019-03-09 01:30发布

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?

标签: bash shell
5条回答
聊天终结者
2楼-- · 2019-03-09 01:52
$ 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.

查看更多
Lonely孤独者°
3楼-- · 2019-03-09 02:02

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.

查看更多
Melony?
4楼-- · 2019-03-09 02:04

Try accessing the environment variable $SUDO_USER

查看更多
成全新的幸福
5楼-- · 2019-03-09 02:09

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).

查看更多
冷血范
6楼-- · 2019-03-09 02:11

The user's home directory would be ~$SUDO_USER. You can use eval as follows:

USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}
查看更多
登录 后发表回答