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:
- Press Escto ensure you are in command mode.
- Enter the following command:
:w !sudo tee %Here’s what this command does:
- :winstructs Vi to write the file.
- !sudoexecutes an external command with- sudoto elevate privileges.
- teereads 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.
 
             
             
            