Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
sudo bar #implicit sudo
$ ./foo1

$ cat foo2
$ sudo ./foo2 #explicit sudo
share|improve this question
It is considered bad practice. su and sudo in a shell script sudo displays typed password in bash script – Bobby Jul 15 '12 at 18:24
OK, I'm convinced. If you turn your comment into a reply I can accept it. – August Karlstrom Jul 15 '12 at 18:46

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:



%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.

share|improve this answer
If used in scripts requiretty should be off, too. In some distributions requiretty is set as default. – Nils Jul 15 '12 at 20:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.