Modify root owned file using vim/vi without switching user

Have you come across the following message when saving/modifying a file in vim, which is actually owned by root and not the user you are using?

'readonly' option is set (add ! to override)

Or

Can't open file for writing

You then realize you need to login as root or use sudo to edit the file again. This can be troublesome as you lose all the changes made to the file and you need to make those changes all again.

This at times is annoying for me as I have to quit and edit the file again using sudo.

The following vim trick does help in this case.

To save a root owned file using vim/vi without quitting the current vim session can be avoided using the following.

When you are saving the file use the following on the vim command line and hit Enter:

:w !sudo tee %

Where,

    * :w - Write a file.
    * !sudo - Call shell sudo command.
    * tee - The output of write (vim :w) command redirected using tee.
    * % - The % is nothing but current file which we are editting. In other words tee command is run as root and it takes standard input and write it to a file represented by %.

It will then ask for the sudo password for the user:

[sudo] password for gagan:

Provide the password and hit Enter

It will then prompt for the file to reloaded (L) in the current session:

Press ENTER or type command to continue
W12: Warning: File "test.sh" has changed and the buffer was changed in Vim as well
See ":help W12" for more info.
[O]K, (L)oad File:

Simply press L and that should be it.

No Comments

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.