Wednesday, April 6, 2022

[SOLVED] How to get $HOME directory of user in bash script root mode?

Issue

file name test.sh

echo $HOME

running in root privilege -> sudo test.sh

expected

/home/username/

but getting

/root

Solution

sudo runs the script as the root-user To get the name of the user who initiated sudo you can call echo $SUDO_USER

To get its home directory:

getent passwd $SUDO_USER | cut -d: -f6


Answered By - ToTheMax
Answer Checked By - Cary Denson (WPSolving Admin)