Get users home directory when they run a script as root

前端 未结 5 970
离开以前
离开以前 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: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).

提交回复
热议问题