Get users home directory when they run a script as root

前端 未结 5 846
离开以前
离开以前 2021-01-31 03:26

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

相关标签:
5条回答
  • 2021-01-31 04:06
    $ 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.

    0 讨论(0)
  • 2021-01-31 04:09

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

    USER_HOME=$(eval echo ~${SUDO_USER})
    echo ${USER_HOME}
    
    0 讨论(0)
  • 2021-01-31 04:12

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

    0 讨论(0)
  • 2021-01-31 04:14

    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.

    0 讨论(0)
  • 2021-01-31 04:17

    Try accessing the environment variable $SUDO_USER

    0 讨论(0)
提交回复
热议问题