Vim / Vi: Save File Without Root Permissions

Objective: You open a file for editing on vi but you do not have write permissions for that file. You make changes and when you try to save changes, you get the infamous error “E212: Can’t open file for writing” from vim / vi editor. You realise that you forgot to execute vi with sudo. How do you save the file without creating a temporary file?

Let’s say you are trying to edit the /etc/passwd file using vi as a normal user. This file is only writable by root based on file permissions.

Normal users will not be able to modify this file in vi. To make changes to this file, vi has to be started as root or with sudo.

If you open the file as a normal user and try to save the file, vi will not be able to save the file due to incorrect permissions and will throw out the error “E212: Can’t open file for writing”. The normal way to overcome this problem is to save the file to a new location, switch to root and overwrite the file. The easier way is to run the following command within vi.

Where:

  • :w – write file, in vi command mode
  • ! – run a shell command within vi
  • sudo – switch to root and execute command
  • tee – executed by sudo as root. It will write contents of buffer in vi to standard output (stdout) and to file specified by ‘%’.
  • % – vi read-only register that contains the name of the current buffer’s file. You can list registers in vi using :registers command
  • > /dev/null – this is optional. This disables tee from printing the file output to screen

Enter your password when prompted by sudo. File will be overwritten with buffer contents in vi. vi will then detect that changes have been made to file and will prompt if you want to reload the file again.

Hit ‘L’ to reload file. All the changes that you had made previously to the file would have been saved.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }