The Glassfish application server provides scripts to administer the application server and also start and stop them and I would like to restrict the root user from running this script. The reason is that some key developers forget to administer the server as the non-privileged user and if they restart the application server as the root user, then the application server has to run by the root user [*].

It isn't an option to avoid giving root access and the developers forget because they are so used to do this on their local machine. I would like the asadmin script to either change to run as the non privileged user or optionally display an error message each time the script is run by root.

Bash shell is used.

[*]: I've tried to fix the rights on files, but even though I've tracked down lots of files which root owns and chmod them, the application experience strange errors and I have to run as root again.

2 Answers 2


Similar to the other answers, but in the direction you wanted.

if [[ $EUID -eq 0 ]]; then
  echo "This script must NOT be run as root" 1>&2
  exit 1

Alternatively, you can use sudo within the script to force execution as the non-privileged user using the -u flag to specify the user to run as. I don't use Glassfish, but here's a proto-example pseudo script.


if [ $1 == "start" ]; then
  sudo -u nobody /usr/bin/glassfish

Hopefully you get the idea. Sorry I don't really know what the script looks like, or the name of the non-privileged user.


@Tshepang has the right idea. I don't know which is most portable, but here are other ways to detect whether the user is root:

id -u

Alternatively, you can simply force it to run as another user with the same parameters:

if [[ "$USER" != appuser ]]
    exec sudo -u appuser "$0" "$@"
  • 1
    This is backward. He wants root to not run this script.
    – bahamat
    Commented Sep 8, 2011 at 14:49
  • D'oh, forgot the sudo bit. Now it should do the job.
    – l0b0
    Commented Sep 9, 2011 at 7:55
  • @TobySpeight No, the script does nothing if the user is root, as intended. I believe your change also results in an extra argument if $@ is empty, and I've changed it to use a pattern found elsewhere.
    – l0b0
    Commented Aug 31, 2017 at 12:33
  • Thanks @TobySpeight, amended. I was sure I'd seen that form somewhere as a way to make sure zero arguments are passed correctly. Also fixed the check, which definitely had a bug (it wasn't a fork bomb, but would simply call itself indefinitely.
    – l0b0
    Commented Aug 31, 2017 at 14:39
  • I'd argue it was a fork bomb, because each instance would fork a new shell for the sudo (it's not using exec) and the parent would wait for it, so you would eventually end up with a full process table. It's still worth putting exec in there (if you don't intend the code after fi to run as the wrong user). Commented Aug 31, 2017 at 15:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .