How To Save A File In Vim / Vi Without Root Permission With sudo

When you’re editing a file in Vim/Vi and you need to save the changes to the file, but you don’t have the necessary permissions, you can use the :w !sudo tee % command to save the file with root permission.

Here are the steps:

  1. Open the file with Vim/Vi: Open the file you want to edit with the Vim/Vi editor.
  2. Make your changes: Edit the file as you normally would.
  3. Save the changes: When you’re ready to save your changes, type the following command:
:w !sudo tee %

This command will save the changes to the file with root permission using the tee command, which writes the standard input to a file and standard output.

  1. Enter your password: When you run the :w !sudo tee % command, you’ll be prompted to enter your password. Enter your password and press Enter.
  2. Verify your changes: After entering your password, your changes should be saved to the file. You can verify your changes by closing the file and opening it again or using another tool to view the file.

Note that this command should be used with caution, as it grants root permission to write to the file. Always make sure that you’re editing the correct file and that you have a backup of the file before making any changes.

Leave a Comment