Vim Tips Wiki
(Move categories to tip template)
(Remove html character entities)
Line 55: Line 55:
   
 
<pre>
 
<pre>
:w !sudo tee % &gt; /dev/null
+
:w !sudo tee % > /dev/null
 
</pre>
 
</pre>
   
Line 61: Line 61:
   
 
<pre>
 
<pre>
sudo vi &lt;file_whose_modes_wouldn't_allow_me_to_write_it&gt;
+
sudo vi <file_whose_modes_wouldn't_allow_me_to_write_it>
 
</pre>
 
</pre>
   

Revision as of 23:38, 29 September 2008

Tip 975 Printable Monobook Previous Next

created August 18, 2005 · complexity basic · author Bernard Pratz · version 6.0


I just wrote a little function that uses sudo and cp to save a file whose modes wouldn't allow me to write it.

Obviously, it preserves the modes of the original file, though it is being rewriten. Of course, this tip has to be used with real caution, as it gets you more power.

TODO:

  • The only real drawback is there's no check for symlinks, and then, the symlink would get removed and replaced by a file with the symlink's modes, which are 777.
  • Another thing that would be nice, would be to integrate it to the interface, to get it work when :w is not enough, or at least having an alias like :wforce, :w!! or :whatever.
function Suedit()
  let fname=tempname()
  exe 'w '.fname
  let owner=system('stat -c%U:%G '.expand("%"))
  let modes=system('stat -c%a '.expand("%"))
  exec '!sudo cp '.fname.' '.expand("%")
  exec '!sudo chmod '.modes." ".expand("%")
  exec '!sudo chown '.owner'" ".expand("%")
endfunction

Comments

Just use:

system('stat -c%a '.expand("%"))
instead of
system('find . -maxdepth 1 -name '.expand("%").' -printf "%m"')

Use script#729 which has had more testing.


It's very simple:

:w !sudo tee %

Minor improvement to prevent tee's stdout from "cluttering" your vim session:

:w !sudo tee % > /dev/null

But why not just:

sudo vi <file_whose_modes_wouldn't_allow_me_to_write_it>