0

I am writing an installation script, and would like it to install in a local directory if the user does not have root access.

specifically, I am looking for the code that goes between the carats (<>)

if [[<do I have root access? = TRUE>]]; then
    .. install .. 
else
    .. install  in $HOME/mylib .. 
fi
David LeBauer
  • 31,011
  • 31
  • 115
  • 189

2 Answers2

2

For bash, you can use the EUID variable:

if [ "$EUID" == 0 ] ; then
    ..something..
else
    ..something else
fi

For a POSIX-compliant solution, use:

if [ "`id -u`" == 0 ] ; then

Although be aware that the usual answer to your question is "don't do that". You never know when someone will decide to run your code in an environment you did not expect... So in general, instead of "check permissions then do something", a better approach is "try to do something and then detect if it fails".

Nemo
  • 70,042
  • 10
  • 116
  • 153
  • @Nemo can you point me in the right direction for using a bash try statement? – David LeBauer Aug 31 '11 at 00:56
  • 1
    On the other hand, sometimes it's better to fail as early as possible. If a script is going to do a bunch of things that can be done by any user, all of which lead up to something that requires root access, I'd rather have it fail immediately. – Keith Thompson Aug 31 '11 at 01:04
  • "Do, or do not. There is no try." Seriously, there is no bash `try` statement. He just meant to try executing a command, and then checking whether it succeeded or not. – Keith Thompson Aug 31 '11 at 01:06
  • @Keith is correct... For a shell script, it can be hard to follow the general principle. "Anything worth doing is worth doing right, unless doing it right would take so long that it wouldn't be worth doing anymore" – Nemo Aug 31 '11 at 03:27
0

Try this:

http://www.cyberciti.biz/tips/shell-root-user-check-script.html

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445