Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get users home directory when they run a script as root

Tags:

bash

shell

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?

like image 832
Peter-W Avatar asked Sep 09 '11 07:09

Peter-W


People also ask

How do I find the home directory in Linux?

On Linux it's often /home/user. However, on some OS's, like OpenSolaris for example, the path is /export/home/user.

How do I find my home directory in Unix?

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.

How do I run a script as a root?

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


2 Answers

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.

like image 161
Michał Šrajer Avatar answered Sep 17 '22 15:09

Michał Šrajer


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

USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}
like image 32
dogbane Avatar answered Sep 17 '22 15:09

dogbane