Amir Raminfar
Amir Raminfar

Reputation: 34169

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. So then I lose my changes by doing :q then sudo !! and make my changes again. Is there a better way to do this?

Upvotes: 25

Views: 12723

Answers (7)

Joel Spolsky
Joel Spolsky

Reputation: 33667

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.

Upvotes: 46

anishsane
anishsane

Reputation: 20980

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.

Upvotes: 0

jkyle
jkyle

Reputation: 2162

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.

Upvotes: 0

thkala
thkala

Reputation: 86373

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.

Upvotes: 2

Adam Maras
Adam Maras

Reputation: 26863

Save the file elsewhere (like your home folder) and then sudo mv it to overwrite the original?

Upvotes: 1

Josh Lee
Josh Lee

Reputation: 177664

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.

Upvotes: 0

Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22814

Save the changes as another file and the make the approrpiate replacement.

Upvotes: 0

Related Questions