Join my Bash scripting course on Udemy 👀

Running sudo commands without a password

April 5, 2021  ‐ 2 min read

The fact that a password is required to run a command with sudo is a useful safety mechanism, which I definitely value on production environments. On my local development machine however, I manage well without the password. You can do so by adding a line like %koen ALL=(ALL:ALL) NOPASSWD: ALL to the sudoers config file, where you swap out my username of course.

First a word on sudo itself, sudo stands for "superuser do" and it is a program that allows you, if you have the permissions, to run commands as a different user. Most often it is used to run commands as the root user.

sudo is just another program that comes installed on your UNIX machine that is configured in the config file located at /etc/sudoers.

Do not edit this file with normal text editor because it can break the sudo command.

You should use the special visudo command/editor to edit the /etc/sudoers config file since it validates whether you have no syntax errors.

$ sudo visudo

This opens up the /etc/sudoers with your preferred editor, and I guess it defaults to vi(m) since the command is visudo :). If you rather use a different editor to edit the sudoers file you can do so by setting the EDITOR environment variable. For example, the following opens the sudoers file with nano.

$ sudo EDITOR=nano visudo

Whether you use vim, nano or something else. The command opens a config file looking somewhat like the following.

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

In order to be able to run sudo without a password you need to add the line %koen ALL=(ALL:ALL) NOPASSWD: ALL to this sudoers file. Where you swap koen for your own username of course. You can get your username by using the command id -un.

So adding that line for your current user leaves the config file something like the following.

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL
%koen   ALL=(ALL:ALL) NOPASSWD: ALL