Using sudo inside a script

Solution 1:

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.