created 2005 · complexity basic · author Bernard Pratz · version 6.0
Sometimes you modify a file, for example from the
/etc directory, then when you try to save the file, you get a permission-denied error. This tip presents some suggestions for using sudo from with Vim, so you can successfullly write the file with temporary privileges.
Of course, this tip has to be used with caution, as it gets you more power.
Suggestion 1[edit | edit source]
If you find you do not have permission to perform
:w, use the following:
:w !sudo tee "%" > /dev/null
You can make a command so
:W invokes sudo:
command W w !sudo tee "%" > /dev/null
Or, if you know about the problem beforehand:
sudoedit path_to_file sudo -e path_to_file
Suggestion 2[edit | edit source]
The following function saves the current file to a temporary file, then copies the new file to replace the original. It preserves the modes of the original file, though it is being rewritten.
function Suedit() let fname=tempname() exec 'w' fname let writetarget=shellescape(expand("%:p")) let owner=shellescape(system('stat --printf=%U:%G ' . writetarget)) let modes=system('stat --printf=c%a ' . writetarget) exec '!sudo cp' shellescape(fname) writetarget exec '!sudo chmod' modes writetarget exec '!sudo chown' owner writetarget endfunction
Warning There is no check for symlinks. A symlink would be removed and replaced by a file with the symlink's modes, which are 777.
Suggestion 3[edit | edit source]
Here is a mapping to save to a
/tmp file, then overwrite the working file.
nnoremap <leader>es :w! /tmp/sudoSave \| let $fileToSave=expand('%') \| let $fileToSaveBackup=expand('%').'~' \| !sudo cp $fileToSave $fileToSaveBackup && sudo cp /tmp/sudoSave $fileToSave<CR><ESC>:e!<CR>
Warning This command will reload the file; you will lose the modifications history (undo will not work, although it does keep a backup).
Note that a backup is made, even when '
nobackup' is set.