Reputation: 29240
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'?
Upvotes: 10
Views: 465
Reputation: 9611
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 -un` != $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.
Upvotes: 1
Reputation: 1995
Example in bash:
if [ `id -u` = 0 ]; then
echo "You are root, go away!"
exit 1
fi
Upvotes: 13
Reputation: 768
In BASH, you can take the output of whoami
and compare it to root
.
Upvotes: 1