How to Safely Edit Sudoers File Using Visudo

The sudoers file controls which users and groups are granted administrative privileges via the sudo command in Linux. Editing this file incorrectly can lead to syntax errors that lock administrators out of root access entirely. This guide explains how to safely configure privilege rules using the dedicated visudo command, which provides lock-file protection and automatic syntax validation to prevent system lockouts.

Why Use visudo?

Directly modifying /etc/sudoers with a standard text editor like nano or vim is dangerous. If a typo or syntax error is saved, the sudo command may stop working immediately.

The visudo command eliminates this risk by:

Launching visudo

To open the sudoers file safely, run:

sudo visudo

By default, visudo opens the configuration file using the system's default text editor (usually vi or nano). If you prefer a specific editor, specify it before the command:

sudo EDITOR=nano visudo

Understanding sudoers Syntax

Rules inside the sudoers file follow a specific pattern:

user_or_group  host=(runas_user:runas_group)  commands

Common Configuration Examples

1. Granting Full Root Privileges to a User

To grant a user named john access to all commands:

john ALL=(ALL:ALL) ALL

2. Granting Full Root Privileges to a Group

To grant root access to all members of the developers group:

%developers ALL=(ALL:ALL) ALL

3. Granting Access Without a Password Prompt

To allow a user to run commands without entering their password, use the NOPASSWD tag:

john ALL=(ALL:ALL) NOPASSWD: ALL

4. Restricting to Specific Commands

To allow a user to run only specific administrative commands (always specify full binary paths):

john ALL=(ALL:ALL) /usr/bin/systemctl restart nginx, /usr/bin/apt update

Handling Syntax Errors

If you make a syntax error while editing and attempt to save, visudo prevents the save and prompts you with options:

>>> /etc/sudoers: syntax error near line 25 <<<
What now? 

The most common options include:

Always choose e to locate and correct the error, or x to discard the changes safely.

Best Practice: Using the /etc/sudoers.d/ Directory

Instead of adding rules directly into /etc/sudoers, it is safer and more modular to place individual configuration files inside the /etc/sudoers.d/ directory.

To safely create or edit a file inside this directory, use the -f flag with visudo:

sudo visudo -f /etc/sudoers.d/custom_rules

Rules applied in /etc/sudoers.d/ must follow the same syntax as the main file, and file names should not contain a period (.) or end with a tilde (~), as sudo will ignore them.