Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest in a shell script to ensure its not run as root?

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'?

like image 727
Jherico Avatar asked Jun 28 '10 19:06

Jherico


2 Answers

Example in bash:

if [ `id -u` = 0 ]; then
  echo "You are root, go away!"
  exit 1
fi
like image 70
cristis Avatar answered Oct 11 '22 07:10

cristis


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

like image 33
Melody Horn Avatar answered Oct 11 '22 08:10

Melody Horn