Search code examples
bashconfigsudopid

How to get the user of the parent process?


I'm writing a program which uses its own config files (in /etc/program/ and ~/.config/program/) The problem is sometimes it needs to be executed as root (so most of the time with sudo) and in this case ~/.config/program is actually in root's directory (/root in my case) I want my program to use the user's config file even if used with sudo. My idea is to first get the parent program's PID (in my case BASH) -- which is normally executed by a normal user -- and then get the name of the user executing the parent program. I easly found out how to get the PPID, but I didn't found how to find the name of the user.

I imagine a script like :

parents_name=$(echo $PPID | *command_which_gives_the_name_from_a_PID*)

. /home/$parents_name/.config/program # includes the user's config file

I hope someone have an awnser !


Solution

  • sudo adds the name of the invoking user to the environment of the command.

    . /home/$SUDO_USER/.config/program
    

    $HOME might already be the same as /home/$SUDO_USER, but there are too many ways to configure sudo to make it the home directory of the target user.

    However, that makes your script dependent on being called by sudo. Better to be explicit and pass the path of the desired configuration to the script as an argument. Something like

    sudo theScript "$HOME/.config/program"
    

    and

    . "$1"