How to Save a Read-Only File in Vi Without Reopening It

How to Save a Read-Only File in Vi Without Reopening It

I often encounter a situation where I start editing a file as a normal user, only to realize that the file is read-only for my current user. Instead of closing the file and reopening it with elevated privileges, I prefer to save my changes directly. Here’s the method I use to save a read-only file in Vi.

Solution

In Vi, follow these steps to save the file with root user privileges:

  1. Press Esc to ensure you are in command mode.
  2. Enter the following command:
:w !sudo tee %

Here’s what this command does:

  • :w instructs Vi to write the file.
  • !sudo executes an external command with sudo to elevate privileges.
  • tee reads from standard input and writes to standard output and files.
  • % stands for the current filename.

This command will prompt you to enter the root user’s password, after which your changes will be saved.