views:

113

answers:

6

Hi,

In my shell script i have the following line:

export PATH=$PATH:/home/$USER/somedir.

Say im logged in as user mike . I need to execute the shell script as root, so i run it as sudo filename.sh, so $USER becomes root in my path in that case .

I want it to be that of the user running the script, i.e. mike instead of root. Is there a way to achieve this ?

Thank You

+5  A: 

Do you have to use /home/$USER, or will $HOME do the trick? IIRC, sudo doesn't override the value of $HOME.

Chris Jester-Young
yes, sudo echo $HOME prints the user home not root home
neuro
A: 

If you're willing to use su instead of sudo, you can do

su -cp filename.sh

to execute the command while preserving your environment.

ire_and_curses
su? That's yuck, because it requires a root password instead of your own password.
Chris Jester-Young
Not if you run su with sudo
smcameron
A: 

You can try using $UID, which should still be set to the user's real ID number and retrieving their name out of the password database based on that.

Steve K
Why not go whole hog and suggest getting the home directory out of the password database? HOME=$(getent passwd $SUDO_UID | cut -d: -f6)
Chris Jester-Young
Yes; then using $HOME seems simpler :)
neuro
A: 

If you need to preserve environnement, you can use the -E option of sudo. But it needs some configuration and security politics ... That applies if the $HOME solution proposed by Chris JY does not apply as it is simpler.

my 2 cents

neuro
+1  A: 

Use $SUDO_USER (if you insist on using $USER directly, set its value as shown):

$ cat script.sh
#!/bin/bash

if [ "$SUDO_USER" != "" ]; then
  USER=$SUDO_USER;
fi

export PATH=$PATH:/home/$USER/somedir

Or cheat using $USER as the first parameter to the script (error checking is an exercise for the reader):

$ cat script.sh
#!/bin/bash
USER=$1

export PATH=$PATH:/home/$USER/somedir

Then:

$ sudo ./script.sh $USER

Or use $HOME, as suggested by Chris Jester-Young. You could use bash to remove the "/home/" prefix, but that would be an ugly hack.

Dave Jarvis
A: 

sudo is different form "root" user. If any user has sudo privileges, that means he has the admin rights that are available with the user "root". That is, using sudo doesn't change the user to root.

Barun