views:

130

answers:

5

I have a script which executes a git-pull when I log in. The problem is, if I su to a different user and preserve my environment with an su -lp, the script gets run again and usually gets messed up for various reasons because I'm the wrong user. Is there a way to determine in a shell script whether or not I'm currently SUing? I'm looking for a way that doesn't involve hard coding my username into the script, which is my current solution. I use Bash and ZSH as shells.

+2  A: 

You could use the output of the who command with the id command:

WHO=`who am i | sed -e 's/ .*//'`
ID_WHO=`id -u $WHO`
ID=`id -u`
if [[ "$ID" = "$ID_WHO" ]]
then
    echo "Not su"
else
    echo "Is su"
fi
martin clayton
You can also use "$UID" environment variable. Thats better because you dont have to take output of any command, so it will be faster..
shadyabhi
if [ $UID -eq 0 ];then ...... fi
shadyabhi
A: 

Well.... on linux, if I su to another user the process su is in the new user's process list.

sudo... doesn't leave such pleasant things for you.

I'm using zsh... but I don't think anything in this is shell specific.

if:

%ps | grep " su$"

returns anything, then you're running in an su'd shell.

Note: there is a space before su$ in that to exclude command simply ending in su. Doesn't guard against any custom program/script called su, though.

SuperMagic
A: 
if test "$(id -u)" = "0"; 
  : # commands executed for root
else
  : # commands executed for non root
fi
William Pursell
But what if you'd SU'd to a different non root user? that's how I understood the question.
SuperMagic
A: 

If you are changing user identities with an suid executable, your real and effective user id will be different. But if use use su (or sudo), they'll both be set to the new user. This means that commands that call getuid() or geteuid() won't be useful.

A better method is to check who owns the terminal the script is being run on. This obviously won't work if the process has detached from it's terminal, but unless the script is being run by a daemon, this is unlikely. Try stat -c %U $(tty). I believe who am i will do the same thing on most Unix-like OSes as well.

ataylor
A: 

You can use "$UID" environment variable.

If its value is ZERO, then the user has SUDO*ed*.. Bcos root as $UID==0

shadyabhi
Except sometimes I su to users other than root...
spitfire