Commands.page Logo

How to Edit Sudoers File Safely in Ubuntu

This guide explains the correct method for modifying system privileges on Ubuntu. You will learn why using the visudo command is critical to prevent lockout, how to add users to the sudo group, and how to grant specific command permissions without compromising system security.

Why Use visudo Instead of Nano or Vim

Never edit the /etc/sudoers file directly using standard text editors like nano or vim. Direct editing bypasses syntax checking. If you save a file with a syntax error, you may lose sudo access entirely, locking yourself out of administrative controls. The visudo command opens the file in a safe mode. It locks the file against multiple edits and performs a syntax check before saving changes.

How to Open the Sudoers File

To begin, open your terminal. Enter the following command to launch the safe editor:

sudo visudo

By default, this opens the file in the nano editor on Ubuntu. If you prefer vim, you can change the default editor by running sudo EDITOR=vim visudo.

Adding a User to Sudo Privileges

To grant a user full administrative rights, scroll to the bottom of the file. Add the following line, replacing username with the actual account name:

username ALL=(ALL:ALL) ALL

To add a user to the existing sudo group instead, ensure this line is uncommented (remove the # at the start):

%sudo ALL=(ALL:ALL) ALL

Then add the user to the group using sudo usermod -aG sudo username.

Granting Specific Command Permissions

You can restrict users to specific commands for better security. For example, to allow a user to run only the apt command without a password, add:

username ALL=(ALL) NOPASSWD: /usr/bin/apt

Saving and Verifying Changes

In nano, press Ctrl + O to save and Ctrl + X to exit. In vim, type :wq and press Enter. Upon exiting, visudo will automatically check the file for syntax errors. If an error is detected, it will warn you and ask if you want to save anyway. Always choose to edit again to fix the mistake. If no errors are found, the new permissions are active immediately.