visudo

On this page 7

visudo is the Linux command that safely edits the sudoers file, the policy that decides which users may run which commands with elevated privileges through sudo. In Linux permissions management, it protects the most sensitive configuration on the system by locking the file, opening a temporary copy and validating its syntax before the new policy replaces the old one.

The reason visudo exists is simple: a single typing error in /etc/sudoers can make sudo refuse to run at all. On systems where the root account is locked, that mistake can lock every administrator out of privileged access, so editing the file directly with an ordinary editor is strongly discouraged.

How visudo protects the sudoers file

visudo follows a lock, copy, edit, validate, install sequence. It first takes an exclusive lock so that two administrators cannot edit the policy at the same time, then copies the current file to a temporary location such as /etc/sudoers.tmp and opens that copy in an editor.

When the editor exits, visudo parses the edited copy with the same grammar that sudo uses. If the parser finds an error, visudo reports the line number and asks what to do: re-edit the file, exit without saving, or save anyway. Only a valid file is moved into place, with the correct owner root, group root and mode 0440.

The table below summarizes each stage and the risk it removes.

StageWhat visudo doesRisk it prevents
LockingAcquires an exclusive lock on the policySimultaneous conflicting edits
Temporary copyEdits a copy, not the live fileHalf-written policy during editing
Syntax checkParses rules, aliases and defaultsBroken sudo after a typo
Ownership and modeSets root ownership and mode 0440Rejected file due to wrong permissions
Atomic installRenames the copy over the originalPartially replaced configuration
Stages of a visudo editing session

Key visudo options and editor selection

visudo accepts a small set of options that cover checking, editing included files and choosing the editor. They are useful both interactively and in automated configuration management.

OptionEffectTypical use
-cChecks syntax without editingValidation in scripts and CI pipelines
-f fileEdits or checks a different fileWorking on a drop-in under /etc/sudoers.d
-sEnables strict checkingCatching undefined aliases
-qSuppresses detailed error messagesQuiet checks in automation
-x fileExports the policy as JSONAuditing rules with other tools
Commonly used visudo options

The editor is chosen from the SUDO_EDITOR, VISUAL and EDITOR environment variables, but only if the editor setting in sudoers allows it. Many distributions restrict this list, because an editor that can spawn a shell could otherwise be used to escape the privileged session. The env_editor default controls whether the environment variables are honored at all.

In configuration management, a common pattern is to write a new drop-in file and then run visudo -cf /path/to/file before installing it. This validates the rule in isolation and prevents a deployment tool from pushing a broken policy to many hosts.

visudo is a policy editor, not a privilege tool on its own. It is easy to confuse with neighboring utilities in the Linux permissions toolbox, so the comparison below clarifies their roles.

ToolPurposeRelation to visudo
visudoSafely edits and checks the sudoers policyThe subject of this entry
sudoRuns a command as another user under the policyEnforces the rules visudo maintains
sudoeditLets users edit specific files with privilegesUses rules written with visudo
suSwitches user with the target account passwordDoes not read sudoers at all
doasLightweight alternative to sudoUses doas.conf, checked with doas -C
polkitAuthorizes actions of system servicesSeparate policy, separate tools
visudo and neighboring tools

A frequent misunderstanding is that sudoedit and visudo are the same thing. sudoedit lets an authorized user edit an arbitrary file through a safe copy mechanism, while visudo is dedicated to the sudoers policy and adds grammar validation that sudoedit does not perform.

Writing safe sudoers rules with visudo

Good practice is to keep the main /etc/sudoers file close to the distribution default and place local rules in drop-in files under `/etc/sudoers.d`, which are read through the @includedir directive. Each drop-in is edited with visudo -f /etc/sudoers.d/name, so it receives the same syntax protection as the main file.

A sudoers rule has the general form who where = (as_whom) what. The decision table below shows typical requirements and the rule pattern that meets them with the principle of least privilege.

RequirementRule patternComment
Full admin rights for a group%admins ALL=(ALL:ALL) ALLPassword required on each use
Restart one service onlydeploy ALL=(root) /usr/bin/systemctl restart appNarrow command scope
Passwordless task for automationbackup ALL=(root) NOPASSWD: /usr/local/bin/snapUse only for fixed, audited scripts
Longer password cacheDefaults timestamp_timeout=10Value in minutes
Command loggingDefaults log_outputRecords session input and output
Typical rule patterns edited with visudo

Commands should be listed with absolute paths, and wildcards in arguments should be avoided because they often allow far more than intended. Rules that permit editors, pagers or interpreters can give a user an unrestricted root shell, even when the rule looks harmless.

Limitations and common mistakes

visudo prevents syntax errors, but it cannot detect logical errors in a policy. A rule that is perfectly valid can still grant too much, too little or the wrong thing.

  • Editing sudoers with a plain editor bypasses locking and validation, which is the most common cause of a broken sudo configuration.
  • Drop-in file names with a dot or a trailing tilde are ignored by @includedir, so rules silently fail to apply.
  • Rule order matters: when several entries match, the last matching entry wins, so a later broad rule can override an earlier restriction.
  • Choosing save anyway after an error reintroduces exactly the risk that visudo was designed to prevent.
  • Allowing shell escapes through tools such as vi, less or find turns a limited rule into full root access.

When sudo is already broken, recovery requires another path to root, such as pkexec visudo on systems with polkit, a root login on the console or booting into rescue mode. Keeping an open root session while testing changes is a simple habit that avoids this situation.

In plain words

Think of sudo as a security guard and the sudoers file as the guard’s list of who may enter which rooms. If someone scribbles on that list and makes it unreadable, the guard lets nobody in, including the building manager.

visudo is the careful way to update the list. It works on a copy, checks that every line makes sense and only then hands the new list to the guard. If something is wrong, it says so and gives a chance to fix it before anyone is locked out.

A real-world example

A web team needs its deployment account to restart the application service on twenty Linux servers without receiving full administrator rights. The operations engineer writes a drop-in file containing deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart webapp.service and runs visudo -cf on it inside the configuration pipeline.

The first run fails because the engineer typed a comma instead of a colon after NOPASSWD. visudo reports the line, the pipeline stops before touching any server, and the corrected file passes on the second attempt. After rollout, the deployment account can restart exactly one service and nothing else, and every use is recorded in the system log, while no administrator lost access at any point.