su and sudo in a shell script

zserge picture zserge · Oct 4, 2010 · Viewed 9.1k times · Source

There is a shell script (/bin/sh, not bash) that requires root permissions for execution.

If it is ran by a normal user it should ask user a password to get root access and re-run itself.

Now it uses the following code:

if [ $(id -u) -ne 0 ]; then su root -- $0 $@ ; ... fi

That works fine, but there are some OS like Ubuntu that has no root password at all. On the other hand, a lot of systems use sudo for root permissions.

The question is: how can the script detect whether to use su or sudo without asking the user to enter too much passwords (e.g. enter sudo password, if it fails - run su).

Answer

Roman Cheplyaka picture Roman Cheplyaka · Oct 5, 2010

It shouldn't. If script requires root privileges, it should be run as root. It's the user's business how he's going to accomplish that -- using su, sudo or some other mechanism.

If you are concerned with security issues and don't want to do everything from root, you can drop root privileges for those parts.