views:

107

answers:

3

I have a Java application executed from a ([ba]sh) shell script and unfortunately sometimes the people responsible for deploying it and starting it fail to switch to the appropriate user before starting the application. In this situation I'd like the application to not run at the very least, and ideally issue a warning not to do that. I thought about trying to alias java or change the path for root to include a fake java which does so, but this might have undesirable side effects and isn't going to be effective easily since the shell script specifies the full path to the java binary.

So, is there a standard idiom in shell scripts for 'don't run if I'm root'?

+9  A: 

Example in bash:

if [ `id -u` = 0 ]; then
  echo "You are root, go away!"
  exit 1
fi
cristis
+1  A: 

In BASH, you can take the output of whoami and compare it to root.

Matt
+1  A: 

I use something like this at the beginning of scripts that I want to be run under a service account:

LUSER='my-service'
if [ `id -u` != $LUSER ]; then
    exec su  $LUSER -s $SHELL -c "$0 $@"
fi

# actual script commands here.

If run as the correct user, execution will continue as planned. If run as root, privileges are dropped to the wanted user-id. Other users will get a password prompt which should tell them that something is wrong.

su -s $SHELL ... is used to override the shell set in /etc/passwrd -- it may be set to /bin/false for the service account.

I have used this on Debian systems, using bash and dash. Feel free to comment if portability can be improved.

hillu
well, I think there isn't a specific user that will be deploying and running the java app... it's important just that it's not root.
cristis