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?
On Linux it's often /home/user. However, on some OS's, like OpenSolaris for example, the path is /export/home/user.
Find User's Home Directory Using Cd Command Executing the cd (change directory) command alone should take you to the home directory of the current Linux user. Another approach is to use cd + tilde (~) should navigate us to the Home directory of the currently logged-in user.
To give root privileges to a user while executing a shell script, we can use the sudo bash command with the shebang. This will run the shell script as a root user. Example: #!/usr/bin/sudo bash ....
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.
The user's home directory would be ~$SUDO_USER
. You can use eval
as follows:
USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With