Using sudo inside a script

sudo

Is it considered good or bad practice to use the sudo command inside a shell script? One advantage is that if the user runs the script as non-root, she or he will be asked for password on demand rather than the script failing. On the other hand, if the user has recently run a command with sudo, the script will implicitly run commands as root which may not be what the user expects.

Here is an example:

$ cat foo1
#!/bin/sh
sudo bar #implicit sudo
$ ./foo1

$ cat foo2
#!/bin/sh
bar
$ sudo ./foo2 #explicit sudo

Best Answer

Using sudo is always a good practice. However there are ways to make the use of sudo better. One methods would be to explicitly allow a specific command to run with elevated privileges.

The following would allow only people in the "users" group to execute the command foo1 without a password.

%users ALL=(ALL) NOPASSWD: /full/path/to/foo1

However it would not allow the execution of foo2 in your above example unless a user entered the correct password.

In addition it is often better to configure sudo to require the user's password and not the root password (I am forgetting the configuration option at this moment), and to not have any entries which can allow for users to escalate their privileges, such as:

ALL ALL=(ALL) ALL

or

%users ALL=(ALL) ALL

The user of a wheel group or a similar group for escalation of any command is a good practice. In the end it is best for the root password to be locked away in a safe, never to be used by anyone (ever) unless the stinky stuff hits the fan.