How to get root access inside Vim

It often happens to forget to use sudo when editing configuration files with vim. You write your modifications and when you want to save, you get the annoying error: “E45: ‘readonly’ option is set (add ! to override)”.

The following oneliner will ask for your password and save the modifications to the edited file:
After you type :w !sudo tee % you are asked to press enter to continue and O, to overwrite. You will still remain in the read only mode, you can only exit vim with :q! (don’t worry, your modifications have already been added)

$ vim /etc/passwd
[:w !sudo tee %]

  • :w saves the file
  • !sudo calls the sudo command
  • tee redirects vim’s output
  • % the current file
Tagged with: , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *




Subscribe to get the latest Linux news and how to guides directly on your e-mail!