Save file as root after editing as non-root
Ok so this happens to me all the time. There has to be a better solution. Let's say you do vim /etc/somefile.conf
and then you do i
but realize you are not sudo
and you can't write. S开发者_如何学Pythono then I lose my changes by doing :q
then sudo !!
and make my changes again. Is there a better way to do this?
Try
:w !sudo tee "%"
The w !
takes the entire file and pipes it into a shell command. The shell command is sudo tee
which runs tee
as superuser. %
is replaced with the current file name. Quotes needed for files that have either spaces or any other special characters in their names.
Depending on the extent of your changes, it might be faster to save (:w
) your file with a different name, and then use sudo
and cat
to overwrite the content of the original file:
sudo sh -c 'cat changed > file'
Note that both cp
and mv
will replace the original file and its attributes (ownership, permissions, ACLs) will be lost. Do not use them unless you know how to fix the permissions afterwards.
Save the file elsewhere (like your home folder) and then sudo mv
it to overwrite the original?
Save the changes as another file and the make the approrpiate replacement.
When vim starts up, the statusbar says [readonly]
, and the first time you try to edit, it says W10: Warning: Changing a readonly file
and pauses for a full second. This is enough warning for me to quit and say sudoedit /etc/somefile.conf
.
You can enforce this with a plugin: Make buffer modifiable state match file readonly state.
I use zsh templates and function completion.
Specifically this one. If I don't have write permissions, it prompts for my sudo password and automatically runs "sudo vim"…amongst other things.
I used this:
function! SaveAsSudo()
let v=winsaveview()
let a=system("stat -c \%a " . shellescape(expand('%')))
let a=substitute(a,"\n","","g")
let a=substitute(a,"\r","","g")
call system("sudo chmod 666 " . shellescape(expand('%')))
w
call system("sudo chmod " . a . " " . shellescape(expand('%')))
call winrestview(v)
endfunction
I have mapped <F2>
to :w<CR>
. & <F8>
to :call SaveAsSudo()<CR>
Only advantage this answer provides over the sudo tee
option is: vim
does not complain about unsaved buffer or file modified externally.
精彩评论